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工具
描述
高性能图片处理,用于调整大小、转换和操作图片。
来源
- 仓库:lovell/sharp
- 许可证:Apache-2.0
安装
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: ✅