在node.js中使用sharp压缩图像

问题描述 投票:0回答:3

我想使用

sharp
 中的 
node.js

调整图像大小和压缩图像

锐利的

jpeg
具有单独的压缩,对于
webp
具有单独的压缩,对于
png
具有单独的压缩。

网页

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
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


7
投票

您可以使用

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 也是

quality
,但由于它是无损格式,因此默认设置为
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})

© www.soinside.com 2019 - 2024. All rights reserved.