image-compression

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Image Compression

图片压缩

Seamless image compression prior to upload with a hybrid approach:
  • Client primary: Squoosh (WASM)
  • Client fallback: Canvas API
  • Server safety net: Sharp
Defaults: max width $1920$px, max size $512$ KB, quality $75$ (adjust down to hit size).
采用混合方案实现上传前的无缝图片压缩:
  • 客户端首选: Squoosh(WASM)
  • 客户端降级方案: Canvas API
  • 服务端安全保障: Sharp
默认配置: 最大宽度1920px,最大体积512 KB,画质75(可下调画质以满足体积限制)。

When to Use

适用场景

✅ Web apps that upload user images and must reduce bandwidth ✅ Need transparent UX (no user action) ✅ Want modern codecs but must support older browsers
✅ 需上传用户图片且必须减少带宽消耗的Web应用 ✅ 需要透明用户体验(无需用户操作) ✅ 希望使用现代编码格式但必须兼容旧版浏览器

When Not to Use

不适用场景

❌ Server-only batch pipelines (use Sharp directly) ❌ Large-scale media processing with complex transforms (use ImageMagick/FFmpeg)
❌ 仅服务端的批量处理流水线(直接使用Sharp即可) ❌ 涉及复杂转换的大规模媒体处理(使用ImageMagick/FFmpeg)

Core Rules

核心规则

  1. Maintain aspect ratio; never upscale.
  2. Target max width $1920$px and max size $512$ KB.
  3. Start at quality $75$; reduce in steps to meet size.
  4. Prefer JPEG for compatibility; try WebP if size remains too large.
  5. Log compression stats (ratio, saved, processing time).
  1. 保持宽高比;绝不放大图片。
  2. 目标限制为最大宽度1920px、最大体积512 KB。
  3. 初始画质设为75;逐步降低画质以满足体积要求。
  4. 优先使用JPEG以保证兼容性;若体积仍过大,尝试使用WebP。
  5. 记录压缩统计数据(压缩比、节省带宽、处理时间)。

Decision Flow

决策流程

  1. Client attempt (Squoosh)
    • Resize → compress → check size.
    • Decrease quality until size limit met.
    • If still too large, try WebP.
  2. Client fallback (Canvas)
    • Resize → toBlob JPEG → reduce quality if needed.
  3. Server fallback (Sharp)
    • Always validate size/dimensions server-side.
    • Re-compress if client output exceeds limits.
  1. 客户端尝试(Squoosh)
    • 调整尺寸 → 压缩 → 检查体积。
    • 降低画质直至符合体积限制。
    • 若体积仍过大,尝试转换为WebP格式。
  2. 客户端降级方案(Canvas)
    • 调整尺寸 → 转换为JPEG Blob → 必要时降低画质。
  3. 服务端降级方案(Sharp)
    • 始终在服务端验证体积与尺寸。
    • 若客户端输出超出限制,重新进行压缩。

Implementation Steps (High Level)

高层面实现步骤

  1. Client compression service
    • Expose
      compressImage(file, options)
      .
    • Use Squoosh with dynamic import.
    • Fallback to Canvas on error.
  2. Upload hook / handler
    • Validate input is image.
    • Compress transparently.
    • Upload compressed blob.
  3. Server middleware
    • Use Sharp to enforce limits.
    • Return 413 if still too large.
    • Attach compression stats to logs.
  1. 客户端压缩服务
    • 暴露
      compressImage(file, options)
      方法。
    • 结合动态导入使用Squoosh。
    • 出错时自动降级到Canvas方案。
  2. 上传钩子/处理器
    • 验证输入是否为图片。
    • 后台透明执行压缩操作。
    • 上传压缩后的Blob对象。
  3. 服务端中间件
    • 使用Sharp执行限制验证。
    • 若体积仍过大,返回413状态码。
    • 将压缩统计数据附加到日志中。

Required Defaults

必填默认配置

  • maxWidth
    : 1920
  • maxHeight
    : 1920
  • maxSize
    : $512 * 1024$
  • quality
    : 75
  • minDimensions
    : 200x200 (server-side)
  • maxWidth
    : 1920
  • maxHeight
    : 1920
  • maxSize
    : $512 * 1024$
  • quality
    : 75
  • minDimensions
    : 200x200(服务端验证)

Anti-Patterns

反模式

  • ❌ Skipping server validation
  • ❌ Uploading original file on failure without logging
  • ❌ Enlarging images
  • ❌ Using blocking UI (must be transparent to user)
  • ❌ 跳过服务端验证
  • ❌ 压缩失败时直接上传原文件且不记录日志
  • ❌ 放大图片
  • ❌ 使用阻塞式UI(必须对用户透明)

References (Load as Needed)

参考文档(按需加载)

  • Client implementation: references/client.md
  • Client usage example: references/client-usage.md
  • Server middleware + routes: references/server.md
  • Storage adapters (S3/local): references/storage.md
  • Security checks: references/security.md
  • Monitoring & analytics: references/monitoring.md
  • Performance targets: references/performance.md
  • Quality examples: references/quality-metrics.md
  • Environment variables: references/env.md
  • Docker (Sharp): references/docker.md
  • Implementation checklist: references/implementation-checklist.md
  • 客户端实现:references/client.md
  • 客户端使用示例:references/client-usage.md
  • 服务端中间件及路由:references/server.md
  • 存储适配器(S3/本地):references/storage.md
  • 安全检查:references/security.md
  • 监控与分析:references/monitoring.md
  • 性能指标:references/performance.md
  • 画质示例:references/quality-metrics.md
  • 环境变量:references/env.md
  • Docker(Sharp):references/docker.md
  • 实现检查清单:references/implementation-checklist.md

Output Expectations

输出预期

  • Client compression completes in $100$–$500$ ms typical
  • Server compression $50$–$200$ ms typical
  • Bandwidth reduction $85$–$97%$
  • 客户端压缩通常耗时100–500毫秒
  • 服务端压缩通常耗时50–200毫秒
  • 带宽减少85–97%

Checklist

检查清单

  • Client: Squoosh primary + Canvas fallback
  • Client: size/dimension limits enforced
  • Server: Sharp validation + compression
  • Logging: compression stats & processing time
  • Storage: image saved with metadata
  • Tests: JPEG/PNG/WebP, large images, mobile
  • 客户端:Squoosh首选 + Canvas降级方案
  • 客户端:已执行体积/尺寸限制
  • 服务端:Sharp验证 + 压缩
  • 日志:记录压缩统计数据及处理时间
  • 存储:图片保存时附带元数据
  • 测试:覆盖JPEG/PNG/WebP、大尺寸图片、移动端场景