Skip to content

Instantly share code, notes, and snippets.

@madhums
Created September 14, 2014 17:37
  • Star 72 You must be signed in to star a gist
  • Fork 16 You must be signed in to fork a gist
Star You must be signed in to star a gist
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);
@madc0w
Copy link

madc0w commented Mar 14, 2016

All this does, as far as I can tell, is write the data string (minus the "data:image/png;base64" prefix) to a file. If I try to view this "image.png" file, it does not appear as an image, as it is not in the correct PNG format.

Do you have any advice on how to write such a string to an image file? png or jpg would be fine.

@dhananjay431
Copy link

dhananjay431 commented Jun 1, 2016

var img = "your base 64 Image String";
var d=new Date().valueOf();
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 5; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));

if("jpeg"==img.split(";")[0].split("/")[1])
{
var imageName = d + '.' + text + '.jpg';
}
if("gif"==.img.split(";")[0].split("/")[1])
{
var imageName = d + '.' + text + '.gif';
}
if("x-icon"==img.split(";")[0].split("/")[1])
{
var imageName = d + '.' + text + '.ico';
}
if("png"==img.split(";")[0].split("/")[1])
{
var imageName = d + '.' + text + '.png';
}
var data =img.replace(/^data:image/\w+;base64,/, "");

var buf = new Buffer(data, 'base64');
fs.writeFile(imageName, buf);
res.send(imageName);

@ooade
Copy link

ooade commented Sep 2, 2016

Thanks! This should do for those having image error

/* 
 * 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==";
// Grab the extension to resolve any image error
var ext = img.split(';')[0].match(/jpeg|png|gif/)[0];
// 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(img, 'base64');
fs.writeFile('image.' + ext, buf);

@Lokesh235
Copy link

Hi,

Above mentioned solution is great.
Can it be possible to store the image in temporary location? I don't want to save the image file in permanent storage.

@rizkiandrianto
Copy link

Struggling and found this (still) works... Thank you...

@navaneethabomma
Copy link

This is working fine.Thank you very much

@vidicj
Copy link

vidicj commented May 25, 2017

@ooade
Line:
var buf = new Buffer(img, 'base64');
should be:
var buf = new Buffer(data, 'base64');

@neilbannet
Copy link

Thanks. Please what is "fs"?

@superpikar
Copy link

@neilbannet fs is a node file-system module. read more about fs here https://nodejs.org/api/fs.html#fs_file_system

@seancrater
Copy link

This saved my butt! Thank you

@adydevil
Copy link

cmt_file is variable which has base64 encoded image and i want to store it as file in my folder as you people have given example i have tried but it throwing me error ..here is my code....:-

    var ext = cmt_img.split(';')[0].match(/jpeg|jpg|png|gif/)[0];
    var data_img = cmt_img.replace(/^data:image\/\w+;base64,/, "");
    var buf = new Buffer(data_img, 'base64');

    fs.writeFile('img_func.jpg',buf,function(err) {
        console.log(err);
    });

it is throws me error-
Error
at readStream (/opt/lampp/htdocs/XXXX/node/node_modules/raw-body/index.js:196:17)
at getRawBody (/opt/lampp/htdocs/XXXX/node/node_modules/raw-body/index.js:106:12)
at read (/opt/lampp/htdocs/XXXX/node/node_modules/body-parser/lib/read.js:76:3)
at urlencodedParser (/opt/lampp/htdocs/XXXX/node/node_modules/body-parser/lib/types/urlencoded.js:115:5)
at Layer.handle [as handle_request] (/opt/lampp/htdocs/XXXX/node/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/opt/lampp/htdocs/XXXX/node/node_modules/express/lib/router/index.js:317:13)
at /opt/lampp/htdocs/XXXX/node/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/opt/lampp/htdocs/XXXX/node/node_modules/express/lib/router/index.js:335:12)
at next (/opt/lampp/htdocs/XXXX/node/node_modules/express/lib/router/index.js:275:10)
at expressInit (/opt/lampp/htdocs/XXXX/node/node_modules/express/lib/middleware/init.js:40:5)

so where is the problew can anyone help

@oinkbark
Copy link

👍

@delismanhulu
Copy link

good

@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