Javad-M
Javad-M

Reputation: 604

Extract png from a base64 image

My image src is base64 data as bellow:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABd4AAAH ...." />

I want to save it as an image (like png format) by nodejs; how is it possible? I am using following code. The src is too big.and when I convert, the image is converted untill its half maybe.

var dt= "iVBORw0KGgoAAAANSUhEUgAABd4AAAH ...." 
let buff = Buffer.from(dt, 'base64');
fs.writeFileSync('./myImage.png', buff);

Upvotes: 0

Views: 779

Answers (2)

Akhmadiy
Akhmadiy

Reputation: 1

It's works but you should add encoding param

var dt= "iVBORw0KGgoAAAANSUhEUgAABd4AAAH ...." 
let buff = Buffer.from(dt, 'base64');
fs.writeFileSync('./myImage.png', buff, {encoding: "base64"});

encoding parameter must be entered for correctly work.

Upvotes: 0

Javohir Abdusattorov
Javohir Abdusattorov

Reputation: 26

You forgot to add extra parameter to write method: "encoding". And value of this parameter should be encoding you want to do, in this example "base64"

In the end, your code should look like this:

var dt= "iVBORw0KGgoAAAANSUhEUgAABd4AAAH ...." 
let buff = Buffer.from(dt, 'base64');
fs.writeFileSync('./myImage.png', buff, { encoding: "base64" });

Upvotes: 1

Related Questions