Skip to content

Instantly share code, notes, and snippets.

@onigetoc
Last active February 22, 2016 17:29
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 onigetoc/0bb3e234f7f2fcf09187 to your computer and use it in GitHub Desktop.
Save onigetoc/0bb3e234f7f2fcf09187 to your computer and use it in GitHub Desktop.
// USE: <img src="img/placeholderimg.jpg" data-src="http://www.website.com/img/pic_mountain.jpg">
// call function: findimg();
// USE: <img src="img/placeholderimg.jpg" data-src="http://www.website.com/img/pic_mountain.jpg">
function findimg() {
var imgEl = document.getElementsByTagName('img');
for (var i = 0; i < imgEl.length; i++) {
if (imgEl[i].getAttribute('data-src')) {
var imgdatasrc = imgEl[i].getAttribute('data-src');
//imgToBlob(imgEl[i], imgdatasrc); // use this for blob
imgToBase64(imgEl[i], imgdatasrc);
}
}
}
function imgToBase64(selector, url, onSuccess, onError) {
var xhr = new XMLHttpRequest();
xhr.responseType = "arraybuffer";
xhr.open("GET", url);
xhr.onload = function() {
var base64, binary, bytes, mediaType;
bytes = new Uint8Array(xhr.response);
//NOTE String.fromCharCode.apply(String, ...
//may cause "Maximum call stack size exceeded"
binary = [].map.call(bytes, function(byte) {
return String.fromCharCode(byte);
}).join('');
mediaType = xhr.getResponseHeader('content-type');
base64 = [
'data:',
mediaType ? mediaType + ';' : '',
'base64,',
btoa(binary)
].join('');
//onSuccess(base64);
console.log(base64)
selector.src = base64;
};
xhr.onerror = onError;
xhr.send();
} // end function imgToBase64
function imgToBlob(selector, imgdatasrc) {
// Simulate a call to Dropbox or other service that can
// return an image as an ArrayBuffer.
var xhr = new XMLHttpRequest();
//alert(imgurl);
// Use JSFiddle logo as a sample image to avoid complicating
// this example with cross-domain issues.
xhr.open("GET", imgdatasrc, true);
// Ask for the result as an ArrayBuffer.
xhr.responseType = "arraybuffer";
xhr.onerror = function(e) {
selector.src = "img/user.png";
//return false
};
xhr.onload = function(e) {
// Obtain a blob: URL for the image data.
var arrayBufferView = new Uint8Array(this.response);
var blob = new Blob([arrayBufferView], {
type: "image/jpeg"
});
var urlCreator = window.URL || window.webkitURL;
var blobimg = urlCreator.createObjectURL(blob);
//selector.setAttribute("src", imgdatasrc);
selector.src = blobimg;
};
xhr.send();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment