Search code examples
javascriptnode.jsimagefabricjsnode-canvas

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


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