高級示例
這裡提供了一些 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);
}
}
}
}