Skip to content

Instantly share code, notes, and snippets.

@ooade
Forked from madhums/base64-image-upload.js
Last active September 2, 2016 20:18
Show Gist options
  • Save ooade/25b10b2410811d13506a41f66ca25d06 to your computer and use it in GitHub Desktop.
Save ooade/25b10b2410811d13506a41f66ca25d06 to your computer and use it in GitHub Desktop.
save base64 encoded image
let fs = require('fs');
// string generated by canvas.toDataURL()
let img = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0"
+ "NAAAAKElEQVQ4jWNgYGD4Twzu6FhFFGYYNXDUwGFpIAk2E4dHDRw1cDgaCAASFOffhEIO"
+ "3gAAAABJRU5ErkJggg==";
// Grab the extension of the file
let ext = img.split(';')[0].match(/jpeg|png|gif/)[0];
// strip off the data: url prefix to get just the base64-encoded bytes
let data = img.replace(/^data.+base64,/, '');
let buf = new Buffer(data, 'base64');
// Write to file with the name(image + . + extension)
fs.writeFile(`image.${ext}`, buf);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment