DengQN·一个普通程序员;
【折腾】超好用的图片处理库 Sharp
2024-01-11 00:52 183
#折腾#node#webp

新博客重构需要对上传的图片做转换到webp压缩体积,
找到个处理库sharp,官网

  1. 安装

直接npm install sharp 即可,需要注意的是,对环境有依赖的,加上参数安装

npm install --include=optional sharp

以避免类似情况

image.png
  1. 转换
import sharp from "sharp";
await sharp(array, {failOnError: false, animated: true})
  .webp()
  .toFile(`xxxx.webp`)

其中,第一个参数,可以是多种类型
image.png

animated: true 可以指出gif 转 webp

转换可能会报错,类似情况

VipsJpeg: Premature end of JPEG file Error message

参数failOnError: false可以解决,也可以具体处理报错:
image.png