如何使用sharp包压缩PNG文件?

3

我正在尝试使用node.js的sharp包压缩PNG文件(大于1MB)。

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

以上代码未能正常工作。我有一个大约3.5MB大小的文件,我试图将其压缩到1MB左右。


“not working properly” 的意思是什么? - Sami Kuhmonen
意思是它没有压缩图像,3.5MB的图像结果为3.5MB。 - napster
也许它无法再压缩了?PNG是无损的。 - Sami Kuhmonen
2个回答

7

我用你提供的代码试过了,它完美地工作,并且在一定程度上压缩了图片。

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

我附上了截图,可以看到图片的大小差异。 屏幕截图


6
我有所遗漏吗?输入文件大小为3MB,输出文件大小也为3MB? - iuliu.net

1
如果你尝试过压缩位图/光栅图像,你会注意到它并不容易被压缩,实际上只有元数据可以被压缩。
PNG是一种无损格式,因此quality参数控制颜色深度。默认情况下,使用quality: 100的无损模式保留完整的颜色深度。当这个百分比减少时,它使用一个颜色palette并减少颜色。
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');
    }
}); 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接