sharp について
sharpは、コード上で画像を扱う開発者向けの高性能画像処理ライブラリです。リサイズや形式変換などに対応し、ストリームによる処理も行えます。
主な機能
- 01画像のリサイズ
- 02WebPと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 対応