XMLHttpRequest base64
XMLHttpRequest Image to base64
by redoak2000
HTML
<img id="myImage" />
CSS
#myImage {
padding: 1px;
background: #4072b4;
}
JavaScript
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://scontent-lga3-1.xx.fbcdn.net/hprofile-xfl1/v/t1.0-1/p50x50/1535038_10152911712752437_2131598232157382790_n.jpg?oh=36dfd554c857b9d8f6b8ab8b3c1bf0ef&oe=5725EE63', true);
// = ../img/logo.png
xhr.responseType = 'arraybuffer';
xhr.onerror = function(e) { alert('error'); };
xhr.onload = function(e) {
if (this.status == 200) {
console.log("2> " + xhr.response);
// console.log("2b> "+ xhr.responseText);
var uInt8Array = new Uint8Array(this.response);
var i = uInt8Array.length;
var biStr = new Array(i);
while (i--) {
biStr[i] = String.fromCharCode(uInt8Array[i]);
}
var data = biStr.join('');
var base64 = window.btoa(data);
console.log("3> " + base64);
xhr.onerror = function(e) { alert('error'); };
$("#myImage").attr("src", "data:image/png;base64," + base64);
}
};
xhr.send();