optimize-images

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Image Optimization for Web Projects

Web项目图片优化

Optimize images for web performance using modern tools. This skill provides scripts and workflows for compressing PNG and JPEG images while maintaining visual quality.
使用现代工具优化图片以提升Web性能。本Skill提供脚本与工作流,可在保持视觉质量的同时压缩PNG和JPEG图片。

When to Use This Skill

适用场景

  • Preparing images for production web deployment
  • Reducing page load times
  • Optimizing public/images directories
  • Batch compressing screenshots, watercolors, photos
  • Auditing image sizes before/after optimization
  • 为生产环境Web部署准备图片
  • 缩短页面加载时间
  • 优化public/images目录
  • 批量压缩截图、水彩画、照片
  • 优化前后的图片尺寸审计

Core Tool: Sharp

核心工具:Sharp

Sharp is the fastest Node.js image processing library, built on libvips. Use it for all image optimization tasks.
Sharp是基于libvips构建的最快的Node.js图片处理库,可用于所有图片优化任务。

Install Sharp

安装Sharp

bash
bun add -d sharp
bash
bun add -d sharp

or

or

npm install -D sharp
undefined
npm install -D sharp
undefined

Quick Start Workflow

快速开始工作流

1. Benchmark Current State

1. 基准状态评估

Before optimization, measure baseline metrics:
bash
undefined
优化前,先测量基准指标:
bash
undefined

Total size and count

总大小与文件数量

du -sh public/images/ find public/images -type f ( -name ".png" -o -name ".jpg" -o -name "*.jpeg" ) | wc -l
du -sh public/images/ find public/images -type f ( -name ".png" -o -name ".jpg" -o -name "*.jpeg" ) | wc -l

Size by format

按格式统计大小

find public/images -name ".png" -exec du -ch {} + | tail -1 find public/images ( -name ".jpg" -o -name "*.jpeg" ) -exec du -ch {} + | tail -1
find public/images -name ".png" -exec du -ch {} + | tail -1 find public/images ( -name ".jpg" -o -name "*.jpeg" ) -exec du -ch {} + | tail -1

Top 20 largest files

前20个最大文件

find public/images -type f ( -name ".png" -o -name ".jpg" ) -exec ls -la {} ; |
awk '{print $5, $9}' | sort -rn | head -20 |
awk '{printf "%6.1fMB %s\n", $1/1048576, $2}'
undefined
find public/images -type f ( -name ".png" -o -name ".jpg" ) -exec ls -la {} ; |
awk '{print $5, $9}' | sort -rn | head -20 |
awk '{printf "%6.1fMB %s\n", $1/1048576, $2}'
undefined

2. Test on Single Image

2. 单张图片测试

Always test optimization settings on one image first:
bash
bun run scripts/optimize-images.ts --file=public/images/largest-image.png --dry-run
始终先在单张图片上测试优化设置:
bash
bun run scripts/optimize-images.ts --file=public/images/largest-image.png --dry-run

3. Run Full Optimization

3. 执行完整优化

After verifying settings work well:
bash
bun run scripts/optimize-images.ts
确认设置生效后:
bash
bun run scripts/optimize-images.ts

4. Verify Results

4. 验证结果

bash
undefined
bash
undefined

Compare before/after

对比优化前后大小

du -sh public/images/
du -sh public/images/

Visually inspect optimized images

视觉检查优化后的图片

Run production build

执行生产构建

bun run build
undefined
bun run build
undefined

Optimization Settings

优化设置

PNG Optimization

PNG优化

Sharp's PNG encoder with palette mode for maximum compression:
typescript
sharp(filePath)
  .png({
    quality: 80,           // 1-100, lower = smaller
    compressionLevel: 9,   // 0-9, higher = more compression
    adaptiveFiltering: true,
    palette: true,         // Use palette for smaller files
  })
  .toBuffer();
Recommended settings:
  • Screenshots: quality 80, compression 9
  • Photos: quality 85, compression 9
  • Icons/logos: quality 90, compression 9 (preserve crispness)
Sharp的PNG编码器启用调色板模式以实现最大压缩:
typescript
sharp(filePath)
  .png({
    quality: 80,           // 1-100,数值越小文件越小
    compressionLevel: 9,   // 0-9,数值越大压缩率越高
    adaptiveFiltering: true,
    palette: true,         // 使用调色板减小文件体积
  })
  .toBuffer();
推荐设置:
  • 截图:quality 80,compression 9
  • 照片:quality 85,compression 9
  • 图标/Logo:quality 90,compression 9(保留清晰度)

JPEG Optimization

JPEG优化

Sharp with mozjpeg for superior compression:
typescript
sharp(filePath)
  .jpeg({
    quality: 80,    // 1-100, lower = smaller
    mozjpeg: true,  // Use mozjpeg encoder
  })
  .toBuffer();
Recommended settings:
  • Photos: quality 75-80
  • Screenshots: quality 80-85
  • Hero images: quality 85
使用mozjpeg的Sharp实现更优压缩:
typescript
sharp(filePath)
  .jpeg({
    quality: 80,    // 1-100,数值越小文件越小
    mozjpeg: true,  // 使用mozjpeg编码器
  })
  .toBuffer();
推荐设置:
  • 照片:quality 75-80
  • 截图:quality 80-85
  • 首屏大图:quality 85

The Optimization Script

优化脚本

Copy
scripts/optimize-images.ts
to the project's scripts directory. The script:
  1. Recursively finds all PNG/JPEG images
  2. Applies compression settings
  3. Overwrites originals (only if smaller)
  4. Reports savings per file
  5. Shows total savings summary
scripts/optimize-images.ts
复制到项目的scripts目录。该脚本具备以下功能:
  1. 递归查找所有PNG/JPEG图片
  2. 应用压缩设置
  3. 仅当优化后文件更小时覆盖原文件
  4. 报告单个文件的空间节省情况
  5. 显示总节省空间摘要

Script Usage

脚本使用方法

bash
undefined
bash
undefined

Dry run (see what would happen)

试运行(查看预期操作)

bun run scripts/optimize-images.ts --dry-run
bun run scripts/optimize-images.ts --dry-run

Test single file

测试单个文件

bun run scripts/optimize-images.ts --file=path/to/image.png
bun run scripts/optimize-images.ts --file=path/to/image.png

Full optimization

完整优化

bun run scripts/optimize-images.ts
undefined
bun run scripts/optimize-images.ts
undefined

Expected Savings

预期节省空间

Typical results for unoptimized web images:
Image TypeTypical Savings
Screenshots (PNG)40-60%
Photos (JPEG)20-40%
Watercolors (PNG)30-50%
Icons (PNG)10-30%
未优化的Web图片通常可实现以下压缩效果:
图片类型典型压缩率
截图(PNG)40-60%
照片(JPEG)20-40%
水彩画(PNG)30-50%
图标(PNG)10-30%

Next.js Considerations

Next.js相关注意事项

Next.js provides automatic image optimization via
next/image
. However, optimizing source images still helps:
  1. Faster builds - Smaller source images = faster processing
  2. Fallback support - Non-Next.js imports still benefit
  3. Reduced storage - Smaller repo size
  4. CDN efficiency - Less data to cache/serve
Keep source images optimized even when using
next/image
.
Next.js通过
next/image
提供自动图片优化,但优化源图片仍有以下好处:
  1. 构建速度更快 - 源图片越小,处理速度越快
  2. 兼容回退方案 - 非Next.js导入的图片仍能受益
  3. 减少存储占用 - 减小仓库体积
  4. CDN效率更高 - 需缓存/分发的数据更少
即使使用
next/image
,也请保持源图片的优化状态。

Workflow Integration

工作流集成

Pre-commit Hook (Optional)

提交前钩子(可选)

Add to
.husky/pre-commit
or git hooks:
bash
undefined
添加到
.husky/pre-commit
或git钩子:
bash
undefined

Warn if large images are being committed

若提交大尺寸图片则发出警告

find public/images -name "*.png" -size +500k -exec echo "Warning: Large image: {}" ;
undefined
find public/images -name "*.png" -size +500k -exec echo "Warning: Large image: {}" ;
undefined

CI/CD Check

CI/CD检查

Add to build pipeline:
bash
undefined
添加到构建流水线:
bash
undefined

Fail if images exceed threshold

若图片总大小超过阈值则构建失败

MAX_SIZE=79 # MB CURRENT=$(du -sm public/images | cut -f1) if [ "$CURRENT" -gt "$MAX_SIZE" ]; then echo "Error: Images exceed ${MAX_SIZE}MB (currently ${CURRENT}MB)" exit 1 fi
undefined
MAX_SIZE=79 # MB CURRENT=$(du -sm public/images | cut -f1) if [ "$CURRENT" -gt "$MAX_SIZE" ]; then echo "Error: Images exceed ${MAX_SIZE}MB (currently ${CURRENT}MB)" exit 1 fi
undefined

Troubleshooting

故障排除

Image Quality Too Low

图片质量过低

Increase quality settings:
  • PNG: Increase
    quality
    to 85-90
  • JPEG: Increase
    quality
    to 85-90
提升质量设置:
  • PNG:将
    quality
    提升至85-90
  • JPEG:将
    quality
    提升至85-90

Transparent PNGs Look Wrong

透明PNG显示异常

Ensure
palette: true
handles transparency correctly. For complex transparency, use:
typescript
.png({ quality: 85, palette: false })
确保
palette: true
正确处理透明效果。对于复杂透明效果,使用:
typescript
.png({ quality: 85, palette: false })

Sharp Installation Issues

Sharp安装问题

On macOS, ensure libvips is available:
bash
brew install vips
Or let sharp download pre-built binaries:
bash
npm rebuild sharp
在macOS上,确保已安装libvips:
bash
brew install vips
或让Sharp下载预构建二进制文件:
bash
npm rebuild sharp

Additional Resources

额外资源

Reference Files

参考文档

  • references/optimization-guide.md
    - Detailed compression algorithms and format comparison
  • references/sharp-api.md
    - Complete sharp API reference for images
  • references/optimization-guide.md
    - 详细的压缩算法与格式对比
  • references/sharp-api.md
    - 完整的Sharp图片API参考

Scripts

脚本

  • scripts/optimize-images.ts
    - Production-ready optimization script
  • scripts/optimize-images.ts
    - 生产级优化脚本

Context Discipline

上下文规范

Do not read optimized images back into context. The script outputs a summary table with file sizes, savings percentages, and totals. Ask the user to visually inspect results if quality verification is needed. Even optimized images can be large enough to fill the context window when processing many files.
请勿将优化后的图片读入上下文。 脚本会输出包含文件大小、节省百分比和总计的摘要表格。若需验证质量,请让用户进行视觉检查。当处理大量文件时,即使是优化后的图片也可能大到填满上下文窗口。

Summary

总结

  1. Install sharp:
    bun add -d sharp
  2. Copy optimization script to project
  3. Benchmark:
    du -sh public/images/
  4. Test:
    bun run scripts/optimize-images.ts --dry-run
  5. Optimize:
    bun run scripts/optimize-images.ts
  6. Verify: Check sizes and visual quality
  7. Commit: Include optimized images in deployment
  1. 安装Sharp:
    bun add -d sharp
  2. 将优化脚本复制到项目中
  3. 基准评估:
    du -sh public/images/
  4. 试运行:
    bun run scripts/optimize-images.ts --dry-run
  5. 执行优化:
    bun run scripts/optimize-images.ts
  6. 验证:检查大小与视觉质量
  7. 提交:将优化后的图片纳入部署