Created
August 28, 2012 14:33
-
-
Save xabolcs/3498536 to your computer and use it in GitHub Desktop.
Converting images to base64
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* To get a base64 encoded data uri from a local file | |
* | |
* @originalauthor brody at MozillaZine | |
* @see http://forums.mozillazine.org/viewtopic.php?p=5091285#p5091285 | |
*/ | |
brodyFile2DataURL = { | |
getFileFromURLSpec: function(aURL) { | |
var ios = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService); | |
var fph = ios.getProtocolHandler("file").QueryInterface(Components.interfaces.nsIFileProtocolHandler); | |
try { return fph.getFileFromURLSpec(aURL).QueryInterface(Components.interfaces.nsILocalFile); } | |
catch(ex) { } | |
return null; | |
}, | |
getDataURLFromIStream: function(aInputStream, aContentType) { | |
var contentType = aContentType || "application/octet-stream"; | |
var binaryStream = Components.classes["@mozilla.org/binaryinputstream;1"].createInstance(Components.interfaces.nsIBinaryInputStream); | |
binaryStream.setInputStream(aInputStream); | |
var encoding = btoa(binaryStream.readBytes(binaryStream.available())); | |
return "data:" + contentType + ";base64," + encoding; | |
}, | |
getDataURLFromFile: function(aFile) { | |
var contentType = Components.classes["@mozilla.org/mime;1"].getService(Components.interfaces.nsIMIMEService).getTypeFromFile(aFile); | |
var inputStream = Components.classes["@mozilla.org/network/file-input-stream;1"].createInstance(Components.interfaces.nsIFileInputStream); | |
inputStream.init(aFile,0x01,0600,0); | |
return this.getDataURIFromIStream(inputStream, contentType); | |
}, | |
asyncGetDataURLFromFile: function(aFile, aCallback) { | |
Components.utils.import("resource://gre/modules/NetUtil.jsm"); | |
var contentType = Components.classes["@mozilla.org/mime;1"].getService(Components.interfaces.nsIMIMEService).getTypeFromFile(aFile); | |
var self = this; | |
NetUtil.asyncFetch(aFile, function (aInputStream, aAsyncFetchResult) { | |
aCallback(self.getDataURIFromIStream(aInputStream, contentType)); | |
}); | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment