【问题标题】:How to compress PNG file using sharp package?如何使用Sharp包压缩PNG文件?
【发布时间】:2018-11-22 13:19:37
【问题描述】:

我正在尝试使用 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 左右。

【问题讨论】:

  • “无法正常工作”是什么意思?
  • 表示不压缩图片,3.5MB图片结果为3.5MB。
  • 可能不能再压缩一点? PNG是无损的

标签: node.js image-processing npm sharp


【解决方案1】:

使用您提供的代码进行了尝试,效果很好,并且还可以在一定程度上压缩图像

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

我附上了截图。它将显示图像大小的差异。

【讨论】:

    【解决方案2】:

    如果您曾尝试压缩位图/光栅图像,您会发现它的压缩效果不佳,它实际上只是压缩了元数据。

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

    【讨论】:

      猜你喜欢
      • 2017-01-28
      • 2012-08-22
      • 2018-02-12
      • 2017-02-22
      • 2012-04-14
      • 1970-01-01
      • 2012-09-02
      • 2011-02-12
      • 1970-01-01
      相关资源
      最近更新 更多