Home > Mobile >  Extract png from a base64 image
Extract png from a base64 image

Time:08-17

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);

CodePudding user response:

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.

CodePudding user response:

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" });
  • Related