简体   繁体   中英

Convert base64 png to jpeg image in Nodejs

I am using FabricJS module in Nodejs . There is a Canvas I am trying to export as jpeg but it wont(giving me a hard time). All I am getting is base64 png data.

Data that starts like

data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAfQAAAH0CAYAAADL1t.....

Is there anyway in nodejs that I can convert this image to jpeg? I googled a lot but couldn get a solution

You can use png-to-jpeg module. Assuming the 'data' is in string form :

const fs = require("fs");

const pngToJpeg = require('png-to-jpeg');
const imgStr = 'data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAfQAAAH0CAYAAADL1t.....';

const buffer = new Buffer(imgStr.split(/,\s*/)[1],'base64');
pngToJpeg({quality: 90})(buffer).then(output => fs.writeFileSync("./some-file.jpeg", output));

Ok, because I'm a professional Googler (just kiding 😂), I found something for you, firstly, you'll have to install ATOB for NodeJS , now, just use it to decode the base64 string, like this :

(function () {
  "use strict";

  var atob = require('atob');
  var b64 = ; //your base64 string
  var bin = atob(b64);
  var fs = require('fs');
  fs.writeFile("./test.jpg", bin, function(err) {
    if(err) {
        return console.log(err);
    }

      console.log("The file was saved!");
   }); 
}());

Actually, I'm not using NodeJS, so I can't tell you more than that, I hope that it will solve your problem!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM