关于 sharp
sharp 是一个用于高性能图像处理的 Node.js 库,面向需要在代码中调整和转换图像的开发者。它支持尺寸调整、格式转换及多种图像操作,也可通过流处理图像。
主要功能
- 01调整图像尺寸
- 02转换为 WebP 和 AVIF
- 03旋转与翻转图像
- 04模糊和锐化处理
- 05添加水印并生成缩略图
- 06通过流处理图像
适用场景
- 01生成指定尺寸的输出图像
- 02将图片转换为现代格式
- 03批量生成不同尺寸的缩略图
- 04处理大型图像流
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ aidotnet/ moyucode --skill sharp安装后在 Claude Code 中输入/sharp确认已加载。
详细介绍
Sharp 工具
描述
高性能图像处理,可用于调整图像大小、转换格式和编辑图像。
来源
- 仓库:lovell/sharp
- 许可证:Apache-2.0
安装
npm install sharp
使用示例
调整图像大小
import sharp from 'sharp';
// Resize to specific dimensions
await sharp('input.jpg')
.resize(800, 600)
.toFile('output.jpg');
// Resize with aspect ratio preserved
await sharp('input.jpg')
.resize(800, null) // Width 800, auto height
.toFile('output.jpg');
// Resize with fit options
await sharp('input.jpg')
.resize(800, 600, {
fit: 'cover', // cover, contain, fill, inside, outside
position: 'center' // center, top, right, bottom, left
})
.toFile('output.jpg');
转换格式
// Convert to WebP
await sharp('input.jpg')
.webp({ quality: 80 })
.toFile('output.webp');
// Convert to AVIF (modern format)
await sharp('input.jpg')
.avif({ quality: 60 })
.toFile('output.avif');
// Convert to PNG with transparency
await sharp('input.jpg')
.png({ compressionLevel: 9 })
.toFile('output.png');
图像编辑
// Rotate and flip
await sharp('input.jpg')
.rotate(90)
.flip()
.toFile('output.jpg');
// Blur and sharpen
await sharp('input.jpg')
.blur(5)
.sharpen()
.toFile('output.jpg');
// Grayscale and tint
await sharp('input.jpg')
.grayscale()
.tint({ r: 255, g: 128, b: 0 })
.toFile('output.jpg');
// Crop
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();
// Resize watermark
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`)
));
}
// Usage
await generateThumbnails('photo.jpg', [64, 128, 256, 512]);
流处理
import { createReadStream, createWriteStream } from 'fs';
// Process large images with streams
createReadStream('large-input.jpg')
.pipe(sharp().resize(1920, 1080).jpeg({ quality: 85 }))
.pipe(createWriteStream('output.jpg'));
标签
image、resize、convert、thumbnail、processing
兼容性
- Codex:✅
- Claude Code:✅
评论
支持 Markdown