Search code examples
node.jsfabricjsimage-compression

How can I reduce the final image size when rendering image in Nodejs using FabricJs object?


Is there any way I can reduce my final image size?

Currently, the image size is around 250-350kb.

I'm planning to bring it to around 50-100 kb.

Is it possible?

My Code in Nodejs

app.get('/loadImage', async function(req, res) {
   
    res.writeHead(200, { 'Content-Type': 'image/png' });
        
    let newObj = req.body.fabricObject
    var canvas = new fabric.StaticCanvas(null, { width: 600, height: 400 });

    canvas.loadFromJSON(newObj, function() {
        canvas.renderAll();

        var stream = canvas.createPNGStream();
        stream.on('data', function(chunk) {
            res.write(chunk);
        });
        stream.on('end', function() {
            res.end();
        });

    });  


});

Solution

  • PNG uses a lossless compression and hence it will always retain its size, unless you resize it. For the same resolution you could use JPEG which uses lossy compression and you can specify it's quality parameter, which would affect the size.

    res.writeHead(200, { 'Content-Type': 'image/jpeg' });
    
    var stream = canvas.createJPEGStream({quality: 100});
    

    Try lowering the quality and see where it meets your size specification.