Skip to content

Instantly share code, notes, and snippets.

@madhums
Created September 14, 2014 17:37
Show Gist options
  • Star 72 You must be signed in to star a gist
  • Fork 16 You must be signed in to fork a gist
  • Save madhums/e749dca107e26d72b64d to your computer and use it in GitHub Desktop.
Save madhums/e749dca107e26d72b64d to your computer and use it in GitHub Desktop.
save base64 encoded image
/*
* Taken from http://stackoverflow.com/questions/5867534/how-to-save-canvas-data-to-file/5971674#5971674
*/
var fs = require('fs');
// string generated by canvas.toDataURL()
var img = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0"
+ "NAAAAKElEQVQ4jWNgYGD4Twzu6FhFFGYYNXDUwGFpIAk2E4dHDRw1cDgaCAASFOffhEIO"
+ "3gAAAABJRU5ErkJggg==";
// strip off the data: url prefix to get just the base64-encoded bytes
var data = img.replace(/^data:image\/\w+;base64,/, "");
var buf = new Buffer(data, 'base64');
fs.writeFile('image.png', buf);
@riccardopirani
Copy link

thanks

@davidtorroija
Copy link

very good!

@padampadampadam
Copy link

how to save this image in excel? Thanks Padam

@tmurvv
Copy link

tmurvv commented Mar 15, 2020

I got a Buffer deprecated warning in NodeJS. I replaced with Buffer.from and it work. Also fixed a callback function warning:

// string generated by canvas.toDataURL()
    var img = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0"
        + "NAAAAKElEQVQ4jWNgYGD4Twzu6FhFFGYYNXDUwGFpIAk2E4dHDRw1cDgaCAASFOffhEIO"
        + "3gAAAABJRU5ErkJggg==";
    // strip off the data: url prefix to get just the base64-encoded bytes
    var data = img.replace(/^data:image\/\w+;base64,/, "");
    var buf = new Buffer.from(data, 'base64');
    fs.writeFile('image.png', buf, err => {
        if (err) throw err;
        console.log('Saved!');
    });

@musta20
Copy link

musta20 commented Jun 21, 2020

is it secure?

@lewisMachilika
Copy link

this is great

@thehieuduong7
Copy link

why do I always have error "Buffer is not defined"??

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment