Skip to content

性能优化示例

这里提供了一些 Sharp 性能优化的示例和最佳实践。

内存优化

流式处理大文件

javascript
import sharp from 'sharp';
import fs from 'fs';

// 流式处理,避免将整个文件加载到内存
fs.createReadStream('large-image.jpg')
  .pipe(sharp().resize(800, 600))
  .pipe(fs.createWriteStream('output.jpg'));

使用 Buffer 而不是文件

javascript
// 对于小文件,使用 Buffer 更高效
const inputBuffer = fs.readFileSync('input.jpg');
const outputBuffer = await sharp(inputBuffer)
  .resize(300, 200)
  .jpeg({ quality: 80 })
  .toBuffer();

fs.writeFileSync('output.jpg', outputBuffer);

及时释放资源

javascript
// 处理完成后及时释放
const image = sharp('input.jpg');
await image.resize(300, 200).toFile('output.jpg');
// image 实例会被自动垃圾回收

并发控制

限制并发数量

javascript
// 设置最大并发数
sharp.concurrency(4);

// 批量处理时控制并发
async function batchProcess(files) {
  const batchSize = 4;
  const results = [];
  
  for (let i = 0; i < files.length; i += batchSize) {
    const batch = files.slice(i, i + batchSize);
    const batchPromises = batch.map(file => 
      sharp(file).resize(300, 200).jpeg().toFile(`output_${file}`)
    );
    
    await Promise.all(batchPromises);
    results.push(...batch);
  }
  
  return results;
}

使用队列处理

javascript
class ImageProcessor {
  constructor(concurrency = 4) {
    this.concurrency = concurrency;
    this.queue = [];
    this.running = 0;
  }
  
  async add(task) {
    return new Promise((resolve, reject) => {
      this.queue.push({ task, resolve, reject });
      this.process();
    });
  }
  
  async process() {
    if (this.running >= this.concurrency || this.queue.length === 0) {
      return;
    }
    
    this.running++;
    const { task, resolve, reject } = this.queue.shift();
    
    try {
      const result = await task();
      resolve(result);
    } catch (error) {
      reject(error);
    } finally {
      this.running--;
      this.process();
    }
  }
}

// 使用示例
const processor = new ImageProcessor(4);

for (const file of files) {
  processor.add(async () => {
    await sharp(file).resize(300, 200).jpeg().toFile(`output_${file}`);
  });
}

缓存优化

缓存处理结果

javascript
const cache = new Map();

async function processWithCache(inputPath, width, height) {
  const key = `${inputPath}_${width}_${height}`;
  
  if (cache.has(key)) {
    return cache.get(key);
  }
  
  const result = await sharp(inputPath)
    .resize(width, height)
    .jpeg({ quality: 80 })
    .toBuffer();
  
  cache.set(key, result);
  return result;
}

清空 Sharp 缓存

javascript
// 定期清空缓存以释放内存
setInterval(() => {
  sharp.cache(false);
}, 60000); // 每分钟清空一次

算法选择

选择合适的调整算法

javascript
// 对于缩小时使用更快的算法
await sharp('input.jpg')
  .resize(300, 200, { kernel: sharp.kernel.cubic })
  .toFile('output.jpg');

// 对于放大时使用更高质量的算法
await sharp('input.jpg')
  .resize(1200, 800, { kernel: sharp.kernel.lanczos3 })
  .toFile('output.jpg');

批量处理优化

javascript
async function optimizedBatchProcess(files) {
  // 按大小分组处理
  const smallFiles = [];
  const largeFiles = [];
  
  for (const file of files) {
    const metadata = await sharp(file).metadata();
    if (metadata.width * metadata.height < 1000000) {
      smallFiles.push(file);
    } else {
      largeFiles.push(file);
    }
  }
  
  // 小文件使用快速算法
  await Promise.all(smallFiles.map(file =>
    sharp(file)
      .resize(300, 200, { kernel: sharp.kernel.cubic })
      .jpeg({ quality: 80 })
      .toFile(`output_${file}`)
  ));
  
  // 大文件使用高质量算法
  await Promise.all(largeFiles.map(file =>
    sharp(file)
      .resize(800, 600, { kernel: sharp.kernel.lanczos3 })
      .jpeg({ quality: 90 })
      .toFile(`output_${file}`)
  ));
}

网络优化

流式响应

javascript
// Express.js 示例
app.get('/image/:filename', async (req, res) => {
  const filename = req.params.filename;
  
  try {
    const imageStream = sharp(`images/${filename}`)
      .resize(300, 200)
      .jpeg({ quality: 80 });
    
    res.set('Content-Type', 'image/jpeg');
    imageStream.pipe(res);
  } catch (error) {
    res.status(404).send('Image not found');
  }
});

条件处理

javascript
app.get('/image/:filename', async (req, res) => {
  const { filename } = req.params;
  const { width, height, quality = 80 } = req.query;
  
  try {
    let image = sharp(`images/${filename}`);
    
    if (width || height) {
      image = image.resize(parseInt(width), parseInt(height));
    }
    
    if (req.headers.accept?.includes('image/webp')) {
      image = image.webp({ quality: parseInt(quality) });
      res.set('Content-Type', 'image/webp');
    } else {
      image = image.jpeg({ quality: parseInt(quality) });
      res.set('Content-Type', 'image/jpeg');
    }
    
    image.pipe(res);
  } catch (error) {
    res.status(404).send('Image not found');
  }
});

监控和调试

性能监控

javascript
async function processWithTiming(inputPath, outputPath) {
  const startTime = Date.now();
  
  try {
    await sharp(inputPath)
      .resize(800, 600)
      .jpeg({ quality: 80 })
      .toFile(outputPath);
    
    const endTime = Date.now();
    console.log(`处理时间: ${endTime - startTime}ms`);
  } catch (error) {
    console.error('处理失败:', error.message);
  }
}

内存使用监控

javascript
const process = require('process');

function logMemoryUsage() {
  const usage = process.memoryUsage();
  console.log('内存使用:', {
    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`
  });
}

// 在处理前后记录内存使用
logMemoryUsage();
await sharp('input.jpg').resize(800, 600).toFile('output.jpg');
logMemoryUsage();

错误处理和重试

重试机制

javascript
async function processWithRetry(inputPath, outputPath, maxRetries = 3) {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      await sharp(inputPath)
        .resize(800, 600)
        .jpeg({ quality: 80 })
        .toFile(outputPath);
      
      console.log(`处理成功,尝试次数: ${attempt}`);
      return;
    } catch (error) {
      console.error(`尝试 ${attempt} 失败:`, error.message);
      
      if (attempt === maxRetries) {
        throw new Error(`处理失败,已重试 ${maxRetries} 次`);
      }
      
      // 等待一段时间后重试
      await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
    }
  }
}

错误分类处理

javascript
async function robustProcess(inputPath, outputPath) {
  try {
    await sharp(inputPath)
      .resize(800, 600)
      .jpeg({ quality: 80 })
      .toFile(outputPath);
  } catch (error) {
    if (error.code === 'VipsForeignLoad') {
      console.error('不支持的图像格式');
    } else if (error.code === 'VipsForeignLoadLimit') {
      console.error('图像太大,尝试缩小');
      // 尝试处理较小的版本
      await sharp(inputPath, { limitInputPixels: 268402689 })
        .resize(400, 300)
        .jpeg({ quality: 80 })
        .toFile(outputPath);
    } else if (error.code === 'ENOSPC') {
      console.error('磁盘空间不足');
    } else {
      console.error('未知错误:', error.message);
    }
  }
}

最佳实践总结

1. 选择合适的处理方式

javascript
// 小文件:直接处理
if (fileSize < 1024 * 1024) {
  await sharp(file).resize(300, 200).toFile(output);
}

// 大文件:流式处理
else {
  fs.createReadStream(file)
    .pipe(sharp().resize(300, 200))
    .pipe(fs.createWriteStream(output));
}

2. 批量处理优化

javascript
// 使用 Promise.all 进行并发处理
const promises = files.map(file => 
  sharp(file).resize(300, 200).jpeg().toFile(`output_${file}`)
);
await Promise.all(promises);

3. 内存管理

javascript
// 定期清理缓存
setInterval(() => {
  sharp.cache(false);
}, 300000); // 每5分钟清理一次

4. 错误处理

javascript
// 总是使用 try-catch
try {
  await sharp(input).resize(300, 200).toFile(output);
} catch (error) {
  console.error('处理失败:', error.message);
  // 提供备用方案
}

相关链接

Released under the Apache 2.0 License.