optimize-images
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseImage 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 sharpbash
bun add -d sharpor
or
npm install -D sharp
undefinednpm install -D sharp
undefinedQuick Start Workflow
快速开始工作流
1. Benchmark Current State
1. 基准状态评估
Before optimization, measure baseline metrics:
bash
undefined优化前,先测量基准指标:
bash
undefinedTotal 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}'
awk '{print $5, $9}' | sort -rn | head -20 |
awk '{printf "%6.1fMB %s\n", $1/1048576, $2}'
undefinedfind 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}'
awk '{print $5, $9}' | sort -rn | head -20 |
awk '{printf "%6.1fMB %s\n", $1/1048576, $2}'
undefined2. 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-run3. Run Full Optimization
3. 执行完整优化
After verifying settings work well:
bash
bun run scripts/optimize-images.ts确认设置生效后:
bash
bun run scripts/optimize-images.ts4. Verify Results
4. 验证结果
bash
undefinedbash
undefinedCompare before/after
对比优化前后大小
du -sh public/images/
du -sh public/images/
Visually inspect optimized images
视觉检查优化后的图片
Run production build
执行生产构建
bun run build
undefinedbun run build
undefinedOptimization 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 to the project's scripts directory. The script:
scripts/optimize-images.ts- Recursively finds all PNG/JPEG images
- Applies compression settings
- Overwrites originals (only if smaller)
- Reports savings per file
- Shows total savings summary
将复制到项目的scripts目录。该脚本具备以下功能:
scripts/optimize-images.ts- 递归查找所有PNG/JPEG图片
- 应用压缩设置
- 仅当优化后文件更小时覆盖原文件
- 报告单个文件的空间节省情况
- 显示总节省空间摘要
Script Usage
脚本使用方法
bash
undefinedbash
undefinedDry 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
undefinedbun run scripts/optimize-images.ts
undefinedExpected Savings
预期节省空间
Typical results for unoptimized web images:
| Image Type | Typical 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 . However, optimizing source images still helps:
next/image- Faster builds - Smaller source images = faster processing
- Fallback support - Non-Next.js imports still benefit
- Reduced storage - Smaller repo size
- CDN efficiency - Less data to cache/serve
Keep source images optimized even when using .
next/imageNext.js通过提供自动图片优化,但优化源图片仍有以下好处:
next/image- 构建速度更快 - 源图片越小,处理速度越快
- 兼容回退方案 - 非Next.js导入的图片仍能受益
- 减少存储占用 - 减小仓库体积
- CDN效率更高 - 需缓存/分发的数据更少
即使使用,也请保持源图片的优化状态。
next/imageWorkflow Integration
工作流集成
Pre-commit Hook (Optional)
提交前钩子(可选)
Add to or git hooks:
.husky/pre-commitbash
undefined添加到或git钩子:
.husky/pre-commitbash
undefinedWarn if large images are being committed
若提交大尺寸图片则发出警告
find public/images -name "*.png" -size +500k -exec echo "Warning: Large image: {}" ;
undefinedfind public/images -name "*.png" -size +500k -exec echo "Warning: Large image: {}" ;
undefinedCI/CD Check
CI/CD检查
Add to build pipeline:
bash
undefined添加到构建流水线:
bash
undefinedFail 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
undefinedMAX_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
undefinedTroubleshooting
故障排除
Image Quality Too Low
图片质量过低
Increase quality settings:
- PNG: Increase to 85-90
quality - JPEG: Increase to 85-90
quality
提升质量设置:
- PNG:将提升至85-90
quality - JPEG:将提升至85-90
quality
Transparent PNGs Look Wrong
透明PNG显示异常
Ensure handles transparency correctly. For complex transparency, use:
palette: truetypescript
.png({ quality: 85, palette: false })确保正确处理透明效果。对于复杂透明效果,使用:
palette: truetypescript
.png({ quality: 85, palette: false })Sharp Installation Issues
Sharp安装问题
On macOS, ensure libvips is available:
bash
brew install vipsOr let sharp download pre-built binaries:
bash
npm rebuild sharp在macOS上,确保已安装libvips:
bash
brew install vips或让Sharp下载预构建二进制文件:
bash
npm rebuild sharpAdditional Resources
额外资源
Reference Files
参考文档
- - Detailed compression algorithms and format comparison
references/optimization-guide.md - - Complete sharp API reference for images
references/sharp-api.md
- - 详细的压缩算法与格式对比
references/optimization-guide.md - - 完整的Sharp图片API参考
references/sharp-api.md
Scripts
脚本
- - Production-ready optimization script
scripts/optimize-images.ts
- - 生产级优化脚本
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
总结
- Install sharp:
bun add -d sharp - Copy optimization script to project
- Benchmark:
du -sh public/images/ - Test:
bun run scripts/optimize-images.ts --dry-run - Optimize:
bun run scripts/optimize-images.ts - Verify: Check sizes and visual quality
- Commit: Include optimized images in deployment
- 安装Sharp:
bun add -d sharp - 将优化脚本复制到项目中
- 基准评估:
du -sh public/images/ - 试运行:
bun run scripts/optimize-images.ts --dry-run - 执行优化:
bun run scripts/optimize-images.ts - 验证:检查大小与视觉质量
- 提交:将优化后的图片纳入部署