Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compress PNG file using sharp package?

I am trying to compress PNG files (above 1MB) using node.js sharp package.

var sharp = require('/usr/local/lib/node_modules/sharp');
sharp('IMG1.png')
.png({ compressionLevel: 9, adaptiveFiltering: true, force: true })
.withMetadata()
.toFile('IMG2.png', function(err){
    if(err){
        console.log(err);
    } else {
        console.log('done');
    }
}); 

Above code is not working properly. I have a file size around 3.5MB and I am trying to compress it around 1MB.

like image 312
napster Avatar asked Oct 19 '25 05:10

napster


2 Answers

Tried withe code you provided, it works perfectly and it also compresses image at certain extend

var sharp = require('sharp');
sharp('input.png')
    .png({ compressionLevel: 9, adaptiveFiltering: true, force: true })
    .withMetadata()
    .toFile('output.png', function(err) {
        console.log(err);
    });

I have attached screenshot. It will show the image size difference. Screenshot

like image 93
Mr. Ratnadeep Avatar answered Oct 21 '25 19:10

Mr. Ratnadeep


If you ever tried to zip a bitmap/raster image you'll notice it doesn't compress well, it really only compresses the metadata.

PNGs are a lossless format, so the quality parameter controls the colour depth. The default is lossless with quality: 100 which retains the full colour depth. When this percentage is reduced, it uses a colour palette and reduces the colours.

var sharp = require('/usr/local/lib/node_modules/sharp');
sharp('IMG1.png')
.withMetadata() // I'm guessing set the metadata before compression?
.png({
  quality: 95, // play around with this number until you get the file size you want
  compression: 6, // this doesn't need to be set, it is by default, no need to increase compression, it will take longer to process
})
.toFile('IMG2.png', function(err){
    if(err){
        console.log(err);
    } else {
        console.log('done');
    }
}); 
like image 20
sonjz Avatar answered Oct 21 '25 19:10

sonjz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!