JSFiddle - React, Tailwind, and code Playground
HTML
<img id="myImage" />
CSS
body {
background: grey;
}
#myImage {
padding: 1em;
background: #4072b4;
}
JavaScript
var converterEngine = function(input){ // fn BLOB => Binary => Base64 ?
var uInt8Array = new Uint8Array(input);
var i = uInt8Array.length;
var biStr = []; //new Array(i);
while (i--) { biStr[i] = String.fromCharCode(uInt8Array[i]); }
var base64 = window.btoa(biStr.join(''));
console.log("base64 produced >>> " + base64); // print-check conversion result
return base64;
}
var getImageBase64 = function (url) {
// 1. Loading file from url:
var xhr = new XMLHttpRequest(url);
xhr.open('GET', url, true); // url is the url of a PNG image.
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
if (this.status == 200) { // 2. When loaded, do:
console.log("1:Response?> " + this.response); // print-check xhr response
var imgBase64 = converterEngine(this.response); // converter
$("#myImage").attr("src", "data:image/png;base64," + imgBase64); // inject data:image in DOM
}
}
xhr.send();
return xhr.onload(); // <fails>: I want to get imgBase64 value as the function's result.
}
getImageBase64('http://fiddle.jshell.net/img/logo.png')
console.log("4>>> " + getImageBase64('http://fiddle.jshell.net/img/logo.png') ) // THIS SHOULD PRINT THE BASE64 CODE (returned resukt of the function getImageBase64)