【问题标题】:Compress image using sharp in node.js在 node.js 中使用Sharp压缩图像
【发布时间】:2018-12-19 20:39:26
【问题描述】:

我想在node.js 中使用sharp 调整图像大小和压缩图像

jpeg 有单独的压缩,webp 有单独的压缩,png 有单独的压缩。

WEBP

sharp('a.jpg')
.resize(1000)
.webp({quality: 80})

JPEG

sharp('_4_.jpg')
 .resize(1000)
 .jpeg({quality: 80})

PNG

sharp('_4_.jpg')
 .resize(1000)
 .png({compressionLevel: 8})

基本上我想压缩和调整图像大小而不检查它们的格式。

sharp 有什么相关的吗?

【问题讨论】:

  • 您为什么不检查扩展名并采取相应措施?如果您想要更精确的检测,您可以读取图像的第一个字节,但我认为没有必要。
  • 是的,这是一个解决方案,但我想这样做而不是检查
  • 我检查但没有找到...这就是我发布问题的原因
  • 不同的格式需要不同的方法解码和编码,所以检查扩展是个好主意。

标签: javascript node.js image-processing image-compression sharp


【解决方案1】:

如果您希望输出格式与输入格式匹配,您应该查看force 选项。

sharp(input)
  .jpeg({ progressive: true, force: false })
  .png({ progressive: true, force: false })
  ...

不支持GIF输出,所以GIF输入默认会变成PNG输出。

其他参考:https://sharp.readthedocs.io/en/v0.17.0/api-output/#jpeg

【讨论】:

    【解决方案2】:

    PNG 也是quality,但由于它是无损格式,默认设置为100。其中 JPG 默认设置为80

    通过减少 PNG 的 quality,它将启用 palette 模式,这将减少编码中捕获的颜色数量。这将为文件提供一些很好的缩减。

    compression 只是 zlib / zip 压缩,还没有发现它做了多少 TBH。

    文档中的所有内容:https://sharp.pixelplumbing.com/api-output#png

    // this will disable loss-less mode, and reduce the colour accuracy to 90%
    // it will also enable the palette
    sharp('_4_.jpg')
     .resize(1000)
     .png({quality: 90})
    
    

    【讨论】:

      【解决方案3】:

      您可以使用metadata方法抓取文件格式并选择相应的优化方法:

      const image = sharp('_4_.jpg')
      const meta = await image.metadata()
      const { format } = meta
      
      const config = {
        jpeg: { quality: 80 },
        webp: { quality: 80 },
        png: {compressionLevel: 8},
      }
      
      await image[format](config[format])
        .resize(1000)
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-01-11
        • 1970-01-01
        • 2019-01-03
        • 2019-08-06
        • 2012-11-16
        • 2019-05-07
        • 2011-02-27
        • 2019-07-24
        相关资源
        最近更新 更多