Bonik Bonik - 3 months ago 22x
Javascript Question

Convert base64 png data to javascript file objects

I have two base64 encoded png's, and i want to compare them using this library:

i think that the best way to do it is to convert the png's into file objects using fileReader,
but i can't figure out how to to this :(

any thoughts?

Thank you!

c69 c69

You can create a Blob from your base64 data, and then read it asDataURL:

var img_b64 = canvas.toDataURL('image/png');
var png = img_b64.split(',')[1];

var the_file = new Blob([window.atob(png)],  {type: 'image/png', encoding: 'utf-8'});

var fr = new FileReader();
fr.onload = function ( oFREvent ) {
    var v =',')[1]; // encoding is messed up here, so we fix it
    v = atob(v);
    var good_b64 = btoa(decodeURIComponent(escape(v)));
    document.getElementById("uploadPreview").src = "data:image/png;base64," + good_b64;

Full example (includes junk code and console log):

Alternatively, you can use .readAsText, it works fine, and its more elegant.. but for some reason text does not sound right ;)

fr.onload = function ( oFREvent ) {
    document.getElementById("uploadPreview").src = "data:image/png;base64,"
    + btoa(;
fr.readAsText(the_file, "utf-8"); // its important to specify encoding here

Full example: