パフォーマンス最適化
Sharp はすでに高性能な画像処理ライブラリですが、いくつかの最適化テクニックにより、さらにパフォーマンスを向上させることができます。
ベンチマーク
Sharp が他の画像処理ライブラリと比較したパフォーマンスの優位性:
- ImageMagick より 4-5 倍高速
- GraphicsMagick より 4-5 倍高速
- メモリ使用量が低い
- ストリーム処理をサポート
メモリ最適化
ストリーム処理の使用
大ファイルの場合、ストリーム処理を使用することでメモリ使用量を大幅に削減できます:
javascript
import fs from 'fs';
// ❌ 推奨しない:ファイル全体をメモリに読み込む
const buffer = fs.readFileSync('large-image.jpg');
await sharp(buffer).resize(800, 600).toFile('output.jpg');
// ✅ 推奨:ストリーム処理を使用
fs.createReadStream('large-image.jpg')
.pipe(sharp().resize(800, 600).jpeg())
.pipe(fs.createWriteStream('output.jpg'));チャンク処理
超大ファイルの場合、チャンク処理が可能です:
javascript
import fs from 'fs';
async function processLargeFile(inputPath, outputPath, chunkSize = 1024 * 1024) {
const pipeline = sharp()
.resize(800, 600)
.jpeg({ quality: 80 });
return new Promise((resolve, reject) => {
const readStream = fs.createReadStream(inputPath, { highWaterMark: chunkSize });
const writeStream = fs.createWriteStream(outputPath);
readStream
.pipe(pipeline)
.pipe(writeStream)
.on('finish', resolve)
.on('error', reject);
});
}
await processLargeFile('large-input.jpg', 'output.jpg');メモリの適時解放
javascript
// 処理完了後に適時にクリーンアップ
async function processImage(inputPath, outputPath) {
const sharpInstance = sharp(inputPath);
try {
await sharpInstance
.resize(800, 600)
.jpeg({ quality: 80 })
.toFile(outputPath);
} finally {
// 手動でクリーンアップ(Node.js は自動的にガベージコレクションしますが)
sharpInstance.destroy();
}
}並行最適化
並行数の制御
javascript
async function processWithConcurrency(files, concurrency = 3) {
const results = [];
for (let i = 0; i < files.length; i += concurrency) {
const batch = files.slice(i, i + concurrency);
const batchPromises = batch.map(file =>
sharp(file)
.resize(300, 200)
.jpeg({ quality: 80 })
.toFile(`processed-${file}`)
);
const batchResults = await Promise.all(batchPromises);
results.push(...batchResults);
}
return results;
}
const files = ['file1.jpg', 'file2.jpg', 'file3.jpg', 'file4.jpg'];
await processWithConcurrency(files, 2);Worker スレッドの使用
CPU 集約的なタスクの場合、Worker スレッドを使用できます:
javascript
import { Worker, isMainThread, parentPort, workerData } from 'worker_threads';
if (isMainThread) {
// メインスレッド
async function processWithWorkers(files, numWorkers = 4) {
const workers = [];
const results = [];
for (let i = 0; i < numWorkers; i++) {
const worker = new Worker('./image-worker.js', {
workerData: { files: files.slice(i * Math.ceil(files.length / numWorkers), (i + 1) * Math.ceil(files.length / numWorkers)) }
});
worker.on('message', (result) => {
results.push(result);
});
workers.push(worker);
}
await Promise.all(workers.map(worker => new Promise(resolve => worker.on('exit', resolve)));
return results;
}
const files = ['file1.jpg', 'file2.jpg', 'file3.jpg'];
await processWithWorkers(files);
} else {
// Worker スレッド
const { files } = workerData;
for (const file of files) {
await sharp(file)
.resize(300, 200)
.jpeg({ quality: 80 })
.toFile(`processed-${file}`);
}
parentPort.postMessage('done');
}キャッシュ最適化
処理結果のキャッシュ
javascript
import crypto from 'crypto';
import fs from 'fs';
class ImageCache {
constructor(cacheDir = './cache') {
this.cacheDir = cacheDir;
if (!fs.existsSync(cacheDir)) {
fs.mkdirSync(cacheDir, { recursive: true });
}
}
generateCacheKey(inputPath, options) {
const content = JSON.stringify({ inputPath, options });
return crypto.createHash('md5').update(content).digest('hex');
}
async getCachedResult(cacheKey) {
const cachePath = `${this.cacheDir}/${cacheKey}.jpg`;
if (fs.existsSync(cachePath)) {
return cachePath;
}
return null;
}
async setCachedResult(cacheKey, resultPath) {
const cachePath = `${this.cacheDir}/${cacheKey}.jpg`;
fs.copyFileSync(resultPath, cachePath);
}
async processImage(inputPath, options) {
const cacheKey = this.generateCacheKey(inputPath, options);
const cached = await this.getCachedResult(cacheKey);
if (cached) {
console.log('キャッシュ結果を使用');
return cached;
}
const outputPath = `output-${Date.now()}.jpg`;
await sharp(inputPath)
.resize(options.width, options.height)
.jpeg({ quality: options.quality })
.toFile(outputPath);
await this.setCachedResult(cacheKey, outputPath);
return outputPath;
}
}
const cache = new ImageCache();
await cache.processImage('input.jpg', { width: 300, height: 200, quality: 80 });アルゴリズム最適化
適切なリサイズアルゴリズムの選択
javascript
// 写真の場合、lanczos3 カーネルを使用
await sharp('photo.jpg')
.resize(800, 600, { kernel: sharp.kernel.lanczos3 })
.toFile('photo-resized.jpg');
// アイコンや線画の場合、nearest カーネルを使用
await sharp('icon.png')
.resize(32, 32, { kernel: sharp.kernel.nearest })
.toFile('icon-resized.png');
// 高速処理が必要な画像の場合、cubic カーネルを使用
await sharp('image.jpg')
.resize(300, 200, { kernel: sharp.kernel.cubic })
.toFile('image-resized.jpg');JPEG 品質の最適化
javascript
// 画像内容に基づいて品質を調整
async function optimizeJPEGQuality(inputPath, outputPath) {
const metadata = await sharp(inputPath).metadata();
// 画像サイズに基づいて品質を調整
let quality = 80;
if (metadata.width > 1920 || metadata.height > 1080) {
quality = 85; // 大画像にはより高品質を使用
} else if (metadata.width < 800 && metadata.height < 600) {
quality = 75; // 小画像にはより低品質を使用可能
}
await sharp(inputPath)
.jpeg({
quality,
progressive: true, // プログレッシブ JPEG
mozjpeg: true // mozjpeg で最適化
})
.toFile(outputPath);
}ネットワーク最適化
異なるサイズの事前生成
javascript
const sizes = [
{ width: 320, suffix: 'sm' },
{ width: 640, suffix: 'md' },
{ width: 1024, suffix: 'lg' },
{ width: 1920, suffix: 'xl' }
];
async function pregenerateSizes(inputPath) {
const promises = sizes.map(size =>
sharp(inputPath)
.resize(size.width, null, { fit: 'inside' })
.jpeg({ quality: 80 })
.toFile(`output-${size.suffix}.jpg`)
);
await Promise.all(promises);
}
await pregenerateSizes('input.jpg');モダンな形式の使用
javascript
// 異なるブラウザをサポートするために複数の形式を生成
async function generateModernFormats(inputPath) {
const promises = [
// JPEG をフォールバックとして
sharp(inputPath)
.resize(800, 600)
.jpeg({ quality: 80 })
.toFile('output.jpg'),
// WebP をモダンブラウザ用に
sharp(inputPath)
.resize(800, 600)
.webp({ quality: 80 })
.toFile('output.webp'),
// AVIF を最新ブラウザ用に
sharp(inputPath)
.resize(800, 600)
.avif({ quality: 80 })
.toFile('output.avif')
];
await Promise.all(promises);
}監視とデバッグ
パフォーマンス監視
javascript
import { performance } from 'perf_hooks';
async function measurePerformance(fn) {
const start = performance.now();
const result = await fn();
const end = performance.now();
console.log(`実行時間: ${end - start}ms`);
return result;
}
await measurePerformance(async () => {
await sharp('input.jpg')
.resize(800, 600)
.jpeg({ quality: 80 })
.toFile('output.jpg');
});メモリ使用監視
javascript
import { performance } from 'perf_hooks';
function getMemoryUsage() {
const usage = process.memoryUsage();
return {
rss: `${Math.round(usage.rss / 1024 / 1024)}MB`,
heapTotal: `${Math.round(usage.heapTotal / 1024 / 1024)}MB`,
heapUsed: `${Math.round(usage.heapUsed / 1024 / 1024)}MB`,
external: `${Math.round(usage.external / 1024 / 1024)}MB`
};
}
console.log('処理前のメモリ使用:', getMemoryUsage());
await sharp('input.jpg')
.resize(800, 600)
.jpeg({ quality: 80 })
.toFile('output.jpg');
console.log('処理後のメモリ使用:', getMemoryUsage());ベストプラクティスのまとめ
- 大ファイルにはストリーム処理を使用
- 並行数を制御
- 処理結果をキャッシュ
- 適切なリサイズアルゴリズムを選択
- 出力形式と品質を最適化
- 一般的なサイズを事前生成
- パフォーマンス指標を監視
パフォーマンス比較
| 操作 | Sharp | ImageMagick | GraphicsMagick |
|---|---|---|---|
| リサイズ | 100ms | 450ms | 420ms |
| 形式変換 | 80ms | 380ms | 360ms |
| フィルタ適用 | 120ms | 520ms | 480ms |
| メモリ使用量 | 低 | 高 | 高 |
次のステップ
- API ドキュメント を確認して、利用可能なすべてのメソッドを学ぶ
- サンプル を学んで、より多くの使い方を学ぶ
- 更新ログ を確認して最新機能を確認する