sharp高性能 Node.js 图像处理模块

联合创作 · 2023-09-23

sharp 是一个高性能的 Node.js 模块,典型用例是将常见格式的大图像转换为较小的、对网络友好的 JPEG、PNG、WebP 和不同尺寸的 AVIF 图像。由于使用了 libvips 库,调整图像大小的速度通常比使用 ImageMagick 和 GraphicsMagick 快 4 到 5 倍。

颜色空间、嵌入的 ICC 配置文件和 alpha 透明通道都得到了正确处理,Lanczos 重采样可确保不会因速度而牺牲质量。除了图像调整大小外,还可以进行旋转、提取、合成和伽马校正等操作。

大多数运行 Node.js >= 12.13.0 的 macOS、Windows 和 Linux 系统不需要任何额外的安装或运行时依赖项。

例子

npm install sharp
const sharp = require('sharp');

回调

sharp(inputBuffer)
  .resize(320, 240)
  .toFile('output.webp', (err, info) => { ... });

Promise

sharp('input.jpg')
  .rotate()
  .resize(200)
  .jpeg({ mozjpeg: true })
  .toBuffer()
  .then( data => { ... })
  .catch( err => { ... });

Async/await

const semiTransparentRedPng = await sharp({
  create: {
    width: 48,
    height: 48,
    channels: 4,
    background: { r: 255, g: 0, b: 0, alpha: 0.5 }
  }
})
  .png()
  .toBuffer();

Stream

const roundedCorners = Buffer.from(
  '<svg><rect x="0" y="0" width="200" height="200" rx="50" ry="50"/></svg>'
);

const roundedCornerResizer =
  sharp()
    .resize(200, 200)
    .composite([{
      input: roundedCorners,
      blend: 'dest-in'
    }])
    .png();

readableStream
  .pipe(roundedCornerResizer)
  .pipe(writableStream);
浏览 3
点赞
评论
收藏
分享

手机扫一扫分享

编辑
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

编辑
举报