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.
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.
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');
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With