API 參考
Sharp 提供了豐富的 API 來處理圖像。本頁面提供了所有可用方法的詳細參考。
構造函數
sharp(input, options?)
創建一個新的 Sharp 實例。
javascript
import sharp from 'sharp';
// 從文件創建
const image = sharp('input.jpg');
// 從 Buffer 創建
const image = sharp(buffer);
// 從 Stream 創建
const image = sharp(stream);
// 創建空白圖像
const image = sharp({
create: {
width: 300,
height: 200,
channels: 4,
background: { r: 255, g: 0, b: 0, alpha: 1 }
}
});輸入元數據
metadata()
獲取圖像的元數據信息。
javascript
const metadata = await sharp('input.jpg').metadata();
console.log(metadata);
// {
// format: 'jpeg',
// width: 1920,
// height: 1080,
// space: 'srgb',
// channels: 3,
// depth: 'uchar',
// density: 72,
// hasProfile: false,
// hasAlpha: false
// }stats()
獲取圖像的統計信息。
javascript
const stats = await sharp('input.jpg').stats();
console.log(stats);
// {
// isOpaque: true,
// dominant: { r: 128, g: 128, b: 128 }
// }輸出選項
toFile(filename, callback?)
將處理後的圖像保存到文件。
javascript
await sharp('input.jpg')
.resize(300, 200)
.toFile('output.jpg');toBuffer(options?, callback?)
將處理後的圖像輸出為 Buffer。
javascript
const buffer = await sharp('input.jpg')
.resize(300, 200)
.jpeg()
.toBuffer();toFormat(format, options?)
設置輸出格式。
javascript
// JPEG
await sharp('input.png')
.jpeg({ quality: 80, progressive: true })
.toFile('output.jpg');
// PNG
await sharp('input.jpg')
.png({ compressionLevel: 9, adaptiveFiltering: true })
.toFile('output.png');
// WebP
await sharp('input.jpg')
.webp({ quality: 80, effort: 6 })
.toFile('output.webp');
// AVIF
await sharp('input.jpg')
.avif({ quality: 80, effort: 4 })
.toFile('output.avif');
// TIFF
await sharp('input.jpg')
.tiff({ quality: 80, compression: 'lzw' })
.toFile('output.tiff');圖像調整
resize(width?, height?, options?)
調整圖像大小。
javascript
// 基本調整
await sharp('input.jpg')
.resize(300, 200)
.toFile('output.jpg');
// 保持寬高比
await sharp('input.jpg')
.resize(300, null)
.toFile('output.jpg');
// 使用適配模式
await sharp('input.jpg')
.resize(300, 200, {
fit: 'cover', // 裁剪以適應
position: 'center', // 居中裁剪
background: { r: 255, g: 255, b: 255, alpha: 1 }
})
.toFile('output.jpg');
// 使用內核
await sharp('input.jpg')
.resize(300, 200, {
kernel: sharp.kernel.lanczos3
})
.toFile('output.jpg');extract(region)
裁剪圖像區域。
javascript
await sharp('input.jpg')
.extract({ left: 100, top: 100, width: 200, height: 200 })
.toFile('cropped.jpg');trim(threshold?)
自動裁剪透明或白色邊緣。
javascript
await sharp('input.png')
.trim()
.toFile('trimmed.png');圖像操作
rotate(angle, options?)
旋轉圖像。
javascript
// 旋轉 90 度
await sharp('input.jpg')
.rotate(90)
.toFile('rotated.jpg');
// 旋轉並填充背景
await sharp('input.jpg')
.rotate(45, { background: { r: 255, g: 255, b: 255, alpha: 1 } })
.toFile('rotated.jpg');flip(flip?)
垂直翻轉圖像。
javascript
await sharp('input.jpg')
.flip()
.toFile('flipped.jpg');flop(flop?)
水平翻轉圖像。
javascript
await sharp('input.jpg')
.flop()
.toFile('flopped.jpg');affine(matrix, options?)
應用仿射變換。
javascript
await sharp('input.jpg')
.affine([[1, 0.3], [0, 1]], { background: { r: 255, g: 255, b: 255, alpha: 1 } })
.toFile('transformed.jpg');濾鏡效果
blur(sigma?)
應用高斯模糊。
javascript
await sharp('input.jpg')
.blur(5)
.toFile('blurred.jpg');sharpen(sigma?, flat?, jagged?)
應用銳化濾鏡。
javascript
await sharp('input.jpg')
.sharpen()
.toFile('sharpened.jpg');
// 自定義銳化參數
await sharp('input.jpg')
.sharpen(1, 1, 2)
.toFile('sharpened.jpg');median(size?)
應用中值濾鏡。
javascript
await sharp('input.jpg')
.median(3)
.toFile('median.jpg');flatten(options?)
合並透明通道。
javascript
await sharp('input.png')
.flatten({ background: { r: 255, g: 255, b: 255 } })
.toFile('flattened.jpg');色彩操作
grayscale(grayscale?)
轉換為灰度圖像。
javascript
await sharp('input.jpg')
.grayscale()
.toFile('grayscale.jpg');negate(negate?)
負片效果。
javascript
await sharp('input.jpg')
.negate()
.toFile('negated.jpg');modulate(options?)
調整亮度、飽和度和色調。
javascript
await sharp('input.jpg')
.modulate({
brightness: 1.2, // 亮度
saturation: 0.8, // 飽和度
hue: 90 // 色調
})
.toFile('modulated.jpg');tint(rgb)
應用色調。
javascript
await sharp('input.jpg')
.tint({ r: 255, g: 0, b: 0 })
.toFile('tinted.jpg');removeAlpha()
移除透明通道。
javascript
await sharp('input.png')
.removeAlpha()
.toFile('no-alpha.jpg');ensureAlpha()
確保有透明通道。
javascript
await sharp('input.jpg')
.ensureAlpha()
.toFile('with-alpha.png');通道操作
bandbool(boolean)
對通道應用布爾運算。
javascript
await sharp('input.jpg')
.bandbool('and')
.toFile('bandbool.jpg');joinChannel(channels)
合並通道。
javascript
await sharp('input.jpg')
.joinChannel(['red.jpg', 'green.jpg', 'blue.jpg'])
.toFile('joined.jpg');extractChannel(channel)
提取單個通道。
javascript
await sharp('input.jpg')
.extractChannel('red')
.toFile('red-channel.jpg');全局屬性
sharp.versions
獲取版本信息。
javascript
console.log(sharp.versions);
// {
// sharp: '0.32.0',
// vips: '8.14.0'
// }sharp.format
獲取支持的格式。
javascript
console.log(sharp.format);
// {
// jpeg: { id: 'jpeg', ... },
// png: { id: 'png', ... },
// webp: { id: 'webp', ... },
// ...
// }sharp.kernel
獲取可用的內核。
javascript
console.log(sharp.kernel);
// {
// nearest: 'nearest',
// cubic: 'cubic',
// mitchell: 'mitchell',
// lanczos2: 'lanczos2',
// lanczos3: 'lanczos3'
// }錯誤處理
javascript
try {
await sharp('input.jpg')
.resize(300, 200)
.toFile('output.jpg');
} catch (error) {
console.error('圖像處理失敗:', error);
}性能優化
流式處理
javascript
const pipeline = sharp()
.resize(300, 200)
.jpeg({ quality: 80 });
fs.createReadStream('large-input.jpg')
.pipe(pipeline)
.pipe(fs.createWriteStream('output.jpg'));並發處理
javascript
const promises = images.map(image =>
sharp(image)
.resize(300, 200)
.jpeg()
.toBuffer()
);
const results = await Promise.all(promises);完整示例
javascript
import sharp from 'sharp';
async function processImage() {
try {
// 獲取元數據
const metadata = await sharp('input.jpg').metadata();
console.log('原始圖像尺寸:', metadata.width, 'x', metadata.height);
// 創建多個版本
const promises = [
// 縮略圖
sharp('input.jpg')
.resize(150, 150, { fit: 'cover' })
.jpeg({ quality: 90 })
.toFile('thumbnail.jpg'),
// 中等尺寸
sharp('input.jpg')
.resize(800, 600, { fit: 'inside' })
.webp({ quality: 80 })
.toFile('medium.webp'),
// 大尺寸
sharp('input.jpg')
.resize(1920, 1080, { fit: 'inside' })
.jpeg({ quality: 85, progressive: true })
.toFile('large.jpg'),
// 灰度版本
sharp('input.jpg')
.grayscale()
.jpeg({ quality: 80 })
.toFile('grayscale.jpg')
];
await Promise.all(promises);
console.log('所有圖像處理完成!');
} catch (error) {
console.error('處理失敗:', error);
}
}
processImage();