使用Node.js中的Sharp压缩图像

21

我想使用sharpnode.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库中有没有相应的功能?

2
为什么不只是检查扩展名并相应地采取行动呢?如果您想要更精确的检测,可以读取图像的前几个字节,但我认为这并不必要。 - Marcos Casagrande
是的,那是一个解决方案,但我想做同样的事情而不是检查。 - Haseeb Ahmad
我检查了但没有找到...这就是为什么我发帖提问的原因。 - Haseeb Ahmad
不同的格式需要不同的解码和编码方法,因此检查文件扩展名是一个好主意。 - primee
3个回答

9
如果您希望输出格式与输入格式相同,您应该查看force选项。
sharp(input)
  .jpeg({ progressive: true, force: false })
  .png({ progressive: true, force: false })
  ...

不支持GIF输出,所以默认情况下将GIF输入转换为PNG输出。

附加参考:https://sharp.pixelplumbing.com/api-output#jpeg


8

您可以使用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)


5

PNG格式同样也是高质量的,但由于它是无损压缩格式,所以默认会设置为100。相比之下,JPG格式默认设置为80

通过降低PNG格式的quality,可以启用palette模式,从而减少编码中捕获的颜色数量,进而有效地减小文件大小。

compression只是zlib / zip压缩,实际上没有发现它起到太大作用。

详见文档: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})


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