sharp高性能 Node.js 圖像處理模塊
sharp 是一個高性能的 Node.js 模塊,典型用例是將常見格式的大圖像轉(zhuǎn)換為較小的、對網(wǎng)絡(luò)友好的 JPEG、PNG、WebP 和不同尺寸的 AVIF 圖像。由于使用了 libvips 庫,調(diào)整圖像大小的速度通常比使用 ImageMagick 和 GraphicsMagick 快 4 到 5 倍。
顏色空間、嵌入的 ICC 配置文件和 alpha 透明通道都得到了正確處理,Lanczos 重采樣可確保不會因速度而犧牲質(zhì)量。除了圖像調(diào)整大小外,還可以進行旋轉(zhuǎn)、提取、合成和伽馬校正等操作。
大多數(shù)運行 Node.js >= 12.13.0 的 macOS、Windows 和 Linux 系統(tǒng)不需要任何額外的安裝或運行時依賴項。
例子
npm install sharp
const sharp = require('sharp');
回調(diào)
sharp(inputBuffer) .resize(320, 240) .toFile('output.webp', (err, info) => { ... });
Promise
sharp('input.jpg') .rotate() .resize(200) .jpeg({ mozjpeg: true }) .toBuffer() .then( data => { ... }) .catch( err => { ... });
Async/await
const semiTransparentRedPng = await sharp({ create: { width: 48, height: 48, channels: 4, background: { r: 255, g: 0, b: 0, alpha: 0.5 } } }) .png() .toBuffer();
Stream
const roundedCorners = Buffer.from( '<svg><rect x="0" y="0" width="200" height="200" rx="50" ry="50"/></svg>' ); const roundedCornerResizer = sharp() .resize(200, 200) .composite([{ input: roundedCorners, blend: 'dest-in' }]) .png(); readableStream .pipe(roundedCornerResizer) .pipe(writableStream);
評論
圖片
表情
