3

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.

napster
  • 349
  • 1
  • 4
  • 16

2 Answers2

7

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

Mr. Ratnadeep
  • 591
  • 4
  • 10
1

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');
    }
}); 
sonjz
  • 4,870
  • 3
  • 42
  • 60