高级示例
这里提供了一些 Sharp 的高级使用示例,包括复杂的图像处理操作。
图像合成
添加水印
javascript
import sharp from 'sharp';
// 添加文字水印
await sharp('input.jpg')
.composite([
{
input: Buffer.from(`
<svg width="200" height="100">
<text x="10" y="50" font-family="Arial" font-size="24" fill="white">
Watermark
</text>
</svg>
`),
top: 10,
left: 10
}
])
.jpeg()
.toFile('output.jpg');
图像叠加
javascript
// 叠加多个图像
await sharp('background.jpg')
.composite([
{
input: 'overlay1.png',
top: 100,
left: 100
},
{
input: 'overlay2.png',
top: 200,
left: 200
}
])
.jpeg()
.toFile('output.jpg');
通道操作
分离通道
javascript
// 分离 RGB 通道
const channels = await sharp('input.jpg').separate();
// 保存各个通道
await sharp(channels[0]).toFile('red-channel.jpg');
await sharp(channels[1]).toFile('green-channel.jpg');
await sharp(channels[2]).toFile('blue-channel.jpg');
合并通道
javascript
// 从单独的通道文件合并
await sharp('red-channel.jpg')
.joinChannel(['green-channel.jpg', 'blue-channel.jpg'])
.toFile('merged.jpg');
颜色空间转换
RGB 转 CMYK
javascript
await sharp('input.jpg')
.toColourspace(sharp.colourspace.cmyk)
.tiff()
.toFile('output.tiff');
转换为 Lab 颜色空间
javascript
await sharp('input.jpg')
.toColourspace(sharp.colourspace.lab)
.tiff()
.toFile('output.tiff');
高级滤镜
自定义锐化
javascript
await sharp('input.jpg')
.sharpen({
sigma: 1,
flat: 1,
jagged: 2
})
.toFile('output.jpg');
伽马校正
javascript
await sharp('input.jpg')
.gamma(2.2)
.toFile('output.jpg');
色调分离
javascript
await sharp('input.jpg')
.tint({ r: 255, g: 0, b: 0 })
.toFile('output.jpg');
多页图像处理
处理 TIFF 多页
javascript
// 处理所有页面
await sharp('multi-page.tiff', { pages: -1 })
.resize(800, 600)
.tiff()
.toFile('output.tiff');
// 处理特定页面
await sharp('multi-page.tiff', { pages: 0 })
.resize(800, 600)
.jpeg()
.toFile('page0.jpg');
处理 PDF
javascript
// 处理 PDF 第一页
await sharp('document.pdf', { pages: 0 })
.resize(800, 600)
.jpeg()
.toFile('page0.jpg');
响应式图像生成
生成多种尺寸
javascript
async function generateResponsiveImages(inputPath) {
const sizes = [
{ width: 320, height: 240, suffix: 'small' },
{ width: 640, height: 480, suffix: 'medium' },
{ width: 1280, height: 960, suffix: 'large' },
{ width: 1920, height: 1440, suffix: 'xlarge' }
];
const promises = sizes.map(async ({ width, height, suffix }) => {
await sharp(inputPath)
.resize(width, height, { fit: 'cover' })
.jpeg({ quality: 80 })
.toFile(`output-${suffix}.jpg`);
});
await Promise.all(promises);
}
生成多种格式
javascript
async function generateMultipleFormats(inputPath) {
const formats = [
{ format: 'jpeg', quality: 80, ext: 'jpg' },
{ format: 'webp', quality: 80, ext: 'webp' },
{ format: 'avif', quality: 80, ext: 'avif' }
];
const promises = formats.map(async ({ format, quality, ext }) => {
const image = sharp(inputPath).resize(800, 600);
switch (format) {
case 'jpeg':
await image.jpeg({ quality }).toFile(`output.${ext}`);
break;
case 'webp':
await image.webp({ quality }).toFile(`output.${ext}`);
break;
case 'avif':
await image.avif({ quality }).toFile(`output.${ext}`);
break;
}
});
await Promise.all(promises);
}
图像分析
获取图像统计信息
javascript
async function analyzeImage(filePath) {
const metadata = await sharp(filePath).metadata();
const stats = await sharp(filePath).stats();
return {
metadata,
stats: {
isOpaque: stats.isOpaque,
dominant: stats.dominant,
channels: stats.channels
}
};
}
检测图像类型
javascript
async function detectImageType(filePath) {
const metadata = await sharp(filePath).metadata();
return {
format: metadata.format,
hasAlpha: metadata.hasAlpha,
isOpaque: metadata.isOpaque,
channels: metadata.channels,
colorSpace: metadata.space
};
}
高级裁剪
智能裁剪
javascript
async function smartCrop(inputPath, outputPath, width, height) {
// 获取图像信息
const metadata = await sharp(inputPath).metadata();
// 计算裁剪区域
const aspectRatio = width / height;
const imageAspectRatio = metadata.width / metadata.height;
let cropWidth, cropHeight, left, top;
if (aspectRatio > imageAspectRatio) {
// 目标更宽,以高度为准
cropHeight = metadata.height;
cropWidth = cropHeight * aspectRatio;
top = 0;
left = (metadata.width - cropWidth) / 2;
} else {
// 目标更高,以宽度为准
cropWidth = metadata.width;
cropHeight = cropWidth / aspectRatio;
left = 0;
top = (metadata.height - cropHeight) / 2;
}
await sharp(inputPath)
.extract({ left: Math.round(left), top: Math.round(top), width: Math.round(cropWidth), height: Math.round(cropHeight) })
.resize(width, height)
.toFile(outputPath);
}
图像优化
自动优化
javascript
async function autoOptimize(inputPath, outputPath) {
const metadata = await sharp(inputPath).metadata();
let image = sharp(inputPath);
// 根据图像类型选择最佳格式
if (metadata.hasAlpha) {
// 有透明度,使用 PNG
image = image.png();
} else {
// 无透明度,使用 JPEG
image = image.jpeg({ quality: 80, progressive: true });
}
await image.toFile(outputPath);
}
渐进式 JPEG
javascript
await sharp('input.jpg')
.jpeg({
quality: 80,
progressive: true,
mozjpeg: true
})
.toFile('output.jpg');
批量高级处理
批量水印
javascript
const fs = require('fs').promises;
async function batchWatermark(inputDir, outputDir, watermarkPath) {
const files = await fs.readdir(inputDir);
for (const file of files) {
if (file.match(/\.(jpg|jpeg|png|webp)$/i)) {
try {
await sharp(path.join(inputDir, file))
.composite([
{
input: watermarkPath,
top: 10,
left: 10
}
])
.jpeg({ quality: 80 })
.toFile(path.join(outputDir, `watermarked_${file}`));
console.log(`水印添加完成: ${file}`);
} catch (error) {
console.error(`处理失败 ${file}:`, error.message);
}
}
}
}
批量格式转换和优化
javascript
async function batchOptimize(inputDir, outputDir) {
const files = await fs.readdir(inputDir);
for (const file of files) {
if (file.match(/\.(jpg|jpeg|png|webp)$/i)) {
try {
const metadata = await sharp(path.join(inputDir, file)).metadata();
const image = sharp(path.join(inputDir, file));
// 根据图像特性选择最佳格式
if (metadata.hasAlpha) {
await image.png({ compressionLevel: 9 }).toFile(path.join(outputDir, file.replace(/\.[^.]+$/, '.png')));
} else {
await image.jpeg({ quality: 80, progressive: true }).toFile(path.join(outputDir, file.replace(/\.[^.]+$/, '.jpg')));
}
console.log(`优化完成: ${file}`);
} catch (error) {
console.error(`处理失败 ${file}:`, error.message);
}
}
}
}