Sharp图片处理工具Skill sharp

Sharp是一个基于Node.js的高性能图片处理库,使用libvips引擎实现极速的图片大小调整、格式转换和图像处理功能。支持JPEG、PNG、WebP、AVIF、TIFF等多种格式,适用于Web开发中的图片优化、缩略图生成、水印添加等场景。关键词:Node.js图片处理、高性能图片压缩、图片格式转换、WebP生成、图片批量处理、图像处理库、前端图片优化、后端图片处理

后端开发 0 次安装 8 次浏览 更新于 2/28/2026

name: sharp description: 高性能Node.js图片处理库。使用libvips最快速地调整JPEG、PNG、WebP、AVIF和TIFF图片大小。 metadata: short-description: 高性能图片处理 source: repository: https://github.com/lovell/sharp license: Apache-2.0 stars: 29k+

Sharp工具

描述

高性能图片处理,用于调整大小、转换和操作图片。

来源

安装

npm install sharp

使用示例

调整图片大小

import sharp from 'sharp';

// 调整到特定尺寸
await sharp('input.jpg')
  .resize(800, 600)
  .toFile('output.jpg');

// 保持宽高比调整大小
await sharp('input.jpg')
  .resize(800, null)  // 宽度800,高度自动
  .toFile('output.jpg');

// 使用适配选项调整大小
await sharp('input.jpg')
  .resize(800, 600, {
    fit: 'cover',      // cover, contain, fill, inside, outside
    position: 'center' // center, top, right, bottom, left
  })
  .toFile('output.jpg');

转换格式

// 转换为WebP
await sharp('input.jpg')
  .webp({ quality: 80 })
  .toFile('output.webp');

// 转换为AVIF(现代格式)
await sharp('input.jpg')
  .avif({ quality: 60 })
  .toFile('output.avif');

// 转换为PNG并带透明度
await sharp('input.jpg')
  .png({ compressionLevel: 9 })
  .toFile('output.png');

图片操作

// 旋转和翻转
await sharp('input.jpg')
  .rotate(90)
  .flip()
  .toFile('output.jpg');

// 模糊和锐化
await sharp('input.jpg')
  .blur(5)
  .sharpen()
  .toFile('output.jpg');

// 灰度化和着色
await sharp('input.jpg')
  .grayscale()
  .tint({ r: 255, g: 128, b: 0 })
  .toFile('output.jpg');

// 裁剪
await sharp('input.jpg')
  .extract({ left: 100, top: 100, width: 500, height: 300 })
  .toFile('output.jpg');

添加水印

async function addWatermark(input: string, watermark: string, output: string) {
  const image = sharp(input);
  const { width, height } = await image.metadata();
  
  // 调整水印大小
  const watermarkBuffer = await sharp(watermark)
    .resize(Math.round(width! * 0.2))
    .toBuffer();
  
  await image
    .composite([{
      input: watermarkBuffer,
      gravity: 'southeast',
      blend: 'over',
    }])
    .toFile(output);
}

生成缩略图

async function generateThumbnails(input: string, sizes: number[]) {
  const image = sharp(input);
  
  await Promise.all(sizes.map(size =>
    image
      .clone()
      .resize(size, size, { fit: 'cover' })
      .jpeg({ quality: 80 })
      .toFile(`thumb-${size}.jpg`)
  ));
}

// 使用
await generateThumbnails('photo.jpg', [64, 128, 256, 512]);

流处理

import { createReadStream, createWriteStream } from 'fs';

// 使用流处理大图片
createReadStream('large-input.jpg')
  .pipe(sharp().resize(1920, 1080).jpeg({ quality: 85 }))
  .pipe(createWriteStream('output.jpg'));

标签

图片, 调整大小, 转换, 缩略图, 处理

兼容性

  • Codex: ✅
  • Claude Code: ✅