Skip to content

Instantly share code, notes, and snippets.

@xabolcs
Created August 28, 2012 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xabolcs/3498536 to your computer and use it in GitHub Desktop.
Save xabolcs/3498536 to your computer and use it in GitHub Desktop.
Converting images to base64
/**
* 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