3

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

Abhinav
  • 8,028
  • 12
  • 48
  • 89

2 Answers2

6

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));
Bulent Vural
  • 2,630
  • 1
  • 13
  • 18
-6

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!

Arthur Guiot
  • 713
  • 10
  • 25
  • 1
    That's a polyfill for the native atob function that's used to convert a base64 string to binary, which does not solve the problem OP was asking. – Tom Jun 05 '17 at 13:51