node sharp 库的使用详解

46 min read

sharp 是一个 Node.js 平台下的高性能图像处理库。它支持图片的裁剪、缩放、旋转、格式转换等多种处理操作,同时具有较高的处理速度和较低的内存消耗。

使用 sharp 库需要先安装依赖:

npm install sharp

接着就可以开始使用 sharp 库了。

创建 sharp 对象

在使用 sharp 库之前,需要先创建一个 sharp 对象:

const sharp = require('sharp'); // 导入库

const image = sharp('path/to/image.jpg'); // 创建 sharp 对象

上面的代码中,我们先导入了 sharp 库,并使用 sharp 函数创建了一个 sharp 对象。其中 path/to/image.jpg 是需要处理的图片路径。

裁剪图片

裁剪图片是图片处理的常见需求之一。sharp 库可以通过 crop 方法实现图片的裁剪操作,具体如下:

image
  .crop(left, top, width, height) // 裁剪,left 表示左上角的 x 坐标,top 表示左上角的 y 坐标,width 表示裁剪后的宽度,height 表示裁剪后的高度
  .toFile('path/to/output.jpg') // 输出文件
  .then(() => {
    console.log('cropped image successfully');
  })
  .catch((err) => {
    console.log(err);
  });

缩放图片

缩放图片也是图片处理的常见需求之一。sharp 库可以通过 resize 方法实现图片的缩放操作,具体如下:

image
  .resize(width, height) // 缩放,width 表示缩放后的宽度,height 表示缩放后的高度
  .toFile('path/to/output.jpg') // 输出文件
  .then(() => {
    console.log('resized image successfully');
  })
  .catch((err) => {
    console.log(err);
  });

旋转图片

旋转图片也是图片处理的常见需求之一。sharp 库可以通过 rotate 方法实现图片的旋转操作,具体如下:

image
  .rotate(degrees) // 旋转,degrees 表示旋转的角度
  .toFile('path/to/output.jpg') // 输出文件
  .then(() => {
    console.log('rotated image successfully');
  })
  .catch((err) => {
    console.log(err);
  });

格式转换

如果需要将图片格式转换为其他格式,可以使用 toFormat 方法,具体如下:

image
  .toFormat('png') // 转换格式为 png
  .toFile('path/to/output.png') // 输出文件
  .then(() => {
    console.log('converted image format successfully');
  })
  .catch((err) => {
    console.log(err);
  });

处理透明度图片

如果图片具有透明度通道,可以使用 flatten 方法将其转换为不透明的图片,具体如下:

image
  .flatten() // 转换为不透明图片
  .toFile('path/to/output.jpg') // 输出文件
  .then(() => {
    console.log('flattened image successfully');
  })
  .catch((err) => {
    console.log(err);
  });

更多操作

除了上述常见的图片处理操作,sharp 库还提供了更多高级的操作,例如锐化、模糊、色彩处理等,可以查看官方文档了解更多详情。

总结

sharp 库提供了高性能的图片处理功能,支持多种常见的图片处理操作,使用起来十分方便。同时,它的 API 友好易用,也提供了很多高级的图片处理操作,适合处理各种不同场景的图片需求。