Skip to content

Instantly share code, notes, and snippets.

@robozevel
Created January 21, 2014 11:25
Show Gist options
  • Save robozevel/8538397 to your computer and use it in GitHub Desktop.
Save robozevel/8538397 to your computer and use it in GitHub Desktop.
Encode images to base64 using FileReader
var encodeImage = (function() {
var DEFAULT_IMAGE = 'data:image/png;base64,',
prefix = "_",
cache = {};
function encode(url, callback) {
var key = prefix + url, value = cache[key];
if (value) {
callback(value);
} else {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (this.response.type.indexOf("image/") === 0) {
var reader = new FileReader();
reader.onload = function (e) {
callback(e.target.result);
};
reader.readAsDataURL(this.response);
} else {
callback(DEFAULT_IMAGE);
}
}
};
xhr.onerror = function() {
callback(DEFAULT_IMAGE);
}
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
}
return function(url, callback) {
url = typeof url === 'string' ? url.trim() : "";
if (url.length > 1) {
if (url.indexOf('data') === 0) {
callback(url);
} else {
encode(url, callback);
}
} else {
callback(DEFAULT_IMAGE);
}
}
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment