Is there a script (on the javascript / client side). This creates URI data on the fly. Now I am creating a data URI using the base64 online creator. And then put this output in a CSS file. But when I change images. It is a lot of work to do this. Is there a script that can do this for me.?
Modern browsers now have good support for base64 encoding and decoding . There are two functions for decoding and encoding base64 strings:
atob()
btoa()
This makes it easy to create uri ie data
var longText = "Lorem ipsum...."; var dataUri = "data:text/plain;base64," + btoa(longText); //a sample api expecting an uri d3.csv(dataUri, function(parsed){ });
There is a script here that can help you
As a complete solution for your scenario, you can use fetch to get a blob representation of your image, and then use FileReader to convert the blob to its base64 representation
fetch
blob
FileReader
base64
// get an image blob from url using fetch let getImageBlob = function(url){ return new Promise( async resolve=>{ let resposne = await fetch( url ); let blob = resposne.blob(); resolve( blob ); }); }; // convert a blob to base64 let blobToBase64 = function(blob) { return new Promise( resolve=>{ let reader = new FileReader(); reader.onload = function() { let dataUrl = reader.result; resolve(dataUrl); }; reader.readAsDataURL(blob); }); } // combine the previous two functions to return a base64 encode image from url let getBase64Image = async function( url ){ let blob = await getImageBlob( url ); let base64 = await blobToBase64( blob ); return base64; } // test time! getBase64Image( 'http://placekitten.com/g/200/300' ).then( base64Image=> console.log( base64Image) );
One way is to create a blob of the object, and then use URL.createObjectURL ()
let a = URL.createObjectURL(new Blob([JSON.stringify({whatever: "String..."}, null, 2)])) console.log(a)