JSFiddle - React, Tailwind, and code Playground
HTML
Below : html with embeded image via data uri. <br />
<img id="myImage" /><hr />
Below : svg-xml with embeded image via data uri (If it works !). <a href="http://fiddle.jshell.net/hugolpz/xGUsu/??/show/light/">html page</a><br />
<svg></svg>
<script src="//d3js.org/d3.v3.min.js"></script>
CSS
body {
background: grey;
}
#myImage {
padding: 1em;
background: #80A0b4;
}
JavaScript
var converterEngine = function (input) { // fn BLOB => Binary => Base64 ?
var uInt8Array = new Uint8Array(input),
i = uInt8Array.length;
var biStr = []; //new Array(i);
while (i--) {
biStr[i] = String.fromCharCode(uInt8Array[i]);
}
var base64 = window.btoa(biStr.join(''));
console.log("2. base64 produced >>> " + base64); // print-check conversion result
return base64;
};
var getImageBase64 = function (url, callback) {
// 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.callback = callback;
xhr.onload = function (e) {
if (this.status == 200) { // 2. When loaded, do:
console.log("1:Loaded response >>> " + this.response); // print-check xhr response
var imgBase64 = converterEngine(this.response); // convert BLOB to base64
this.callback(imgBase64); //execute callback function with data
}
};
xhr.send();
};
//HTML part
getImageBase64('http://fiddle.jshell.net/img/logo.png', function (data) {
$("#myImage").attr("src", "data:image/png;base64," + data); // inject data:image in DOM
// data:[<mime type>][;charset=<charset>][;base64],<encoded data>
})
//SVG part
getImageBase64('http://fiddle.jshell.net/img/logo.png', function (data) {
var width = 500, height = width/2;
var svg = d3.select("svg").attr("width",width).attr("style","background:#80A0b4");
svg.attr(':xmlns','http://www.w3.org/2000/svg')
.attr(':xmlns:xlink','http://www.w3.org/1999/xlink');
var g = svg.append("g").append("image")
.attr("width", width / 2)
.attr(":xlink:href", "data:image/png;base64," + data); // replace link by data URI
})