Skip to content

node.js 使用 sharp

​ sharp 是基于 node.js 的图像处理工具。

文档:https://sharp.nodejs.cn/install

1.安装

问题

在安装时出现该问题:

shell
sharp: Installation error: unable to verify the first certificate
sharp: Installation error: unable to verify the first certificate

1.取消 ssl 验证

npm config set strict-ssl=false
npm config set strict-ssl=false

2.换源

​ 可以专门给对应包换源,因为 sharp 是基于 libvips 的,所以两个都需要换源处理。

shell
npm config set sharp_libvips_binary_host "https://npmmirror.com/mirrors/sharp-libvips"
npm config set sharp_binary_host "https://npmmirror.com/mirrors/sharp"
npm config set sharp_libvips_binary_host "https://npmmirror.com/mirrors/sharp-libvips"
npm config set sharp_binary_host "https://npmmirror.com/mirrors/sharp"

2.使用

基本看看文档就行。

例如压缩图片质量

ts
// 通过sharp读出文件
const image = sharp(filePath);
// 压缩文件质量
image.jpeg({ quality });
image.toBuffer().then(
  (data) => {
    // 响应数据
    res.send(data);
  },
  (error) => {
    res.setHeader("content-type", "application/json");
    new Logger().error(error);
    throw new InternalServerErrorException(tips.staticFileError);
  }
);
// 通过sharp读出文件
const image = sharp(filePath);
// 压缩文件质量
image.jpeg({ quality });
image.toBuffer().then(
  (data) => {
    // 响应数据
    res.send(data);
  },
  (error) => {
    res.setHeader("content-type", "application/json");
    new Logger().error(error);
    throw new InternalServerErrorException(tips.staticFileError);
  }
);