cloudflare-images

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Cloudflare Images

Cloudflare Images

Status: Production Ready ✅ | Version: 3.0.0 | Last Verified: 2025-12-27

状态:生产就绪 ✅ | 版本:3.0.0 | 最后验证时间:2025-12-27

What Is Cloudflare Images?

什么是Cloudflare Images?

Two powerful features:
  1. Images API: Upload, store, serve images globally
  2. Image Transformations: Resize/optimize ANY image
Key benefits:
  • Global CDN delivery
  • Automatic WebP/AVIF conversion
  • Up to 100 variants
  • Direct creator upload (no API keys in frontend)
  • Signed URLs for private images
  • Transform any image via URL or Workers

它包含两大核心功能:
  1. Images API:在全球范围内上传、存储、分发图片
  2. 图片转换:调整大小/优化任意图片
核心优势
  • 全球CDN分发
  • 自动转换为WebP/AVIF格式
  • 支持最多100种图片变体
  • 直接创作者上传(前端无需暴露API密钥)
  • 为私有图片生成签名URL
  • 通过URL或Workers转换任意图片

Quick Start (5 Minutes)

快速入门(5分钟)

1. Enable Cloudflare Images

1. 启用Cloudflare Images

Dashboard → ImagesEnable
Get your Account ID and create API token (Cloudflare Images: Edit permission)
控制台 → Images启用
获取你的账户ID并创建API令牌(需拥有Cloudflare Images:编辑权限)

2. Upload Image

2. 上传图片

bash
curl --request POST \
  --url https://api.cloudflare.com/client/v4/accounts/<ACCOUNT_ID>/images/v1 \
  --header 'Authorization: Bearer <API_TOKEN>' \
  --header 'Content-Type: multipart/form-data' \
  --form 'file=@./image.jpg'
CRITICAL: Use
multipart/form-data
, not JSON
bash
curl --request POST \
  --url https://api.cloudflare.com/client/v4/accounts/<ACCOUNT_ID>/images/v1 \
  --header 'Authorization: Bearer <API_TOKEN>' \
  --header 'Content-Type: multipart/form-data' \
  --form 'file=@./image.jpg'
重要提示:请使用
multipart/form-data
格式,而非JSON

3. Serve Image

3. 分发图片

html
<img src="https://imagedelivery.net/<ACCOUNT_HASH>/<IMAGE_ID>/public" />
html
<img src="https://imagedelivery.net/<ACCOUNT_HASH>/<IMAGE_ID>/public" />

4. Enable Transformations

4. 启用转换功能

Dashboard → ImagesTransformationsEnable for zone
Transform ANY image:
html
<img src="/cdn-cgi/image/width=800,quality=85/uploads/photo.jpg" />
控制台 → Images转换为域名启用
转换任意图片:
html
<img src="/cdn-cgi/image/width=800,quality=85/uploads/photo.jpg" />

5. Transform via Workers

5. 通过Workers进行转换

typescript
export default {
  async fetch(request: Request): Promise<Response> {
    return fetch("https://example.com/image.jpg", {
      cf: {
        image: {
          width: 800,
          quality: 85,
          format: "auto"  // WebP/AVIF
        }
      }
    });
  }
};
Load
references/setup-guide.md
for complete walkthrough.

typescript
export default {
  async fetch(request: Request): Promise<Response> {
    return fetch("https://example.com/image.jpg", {
      cf: {
        image: {
          width: 800,
          quality: 85,
          format: "auto"  // WebP/AVIF
        }
      }
    });
  }
};
如需完整流程,请查看
references/setup-guide.md

The 3 Core Features

三大核心功能

Feature 1: Images API (Upload & Storage)

功能1:Images API(上传与存储)

Upload methods:
  1. File upload (server-side)
  2. Upload via URL (ingest from external)
  3. Direct creator upload (user uploads, no API keys)
Load
templates/upload-api-basic.ts
for file upload example.
Load
references/direct-upload-complete-workflow.md
for user uploads.
上传方式
  1. 文件上传(服务端)
  2. 通过URL上传(从外部导入)
  3. 直接创作者上传(用户自主上传,无需暴露API密钥)
文件上传示例请查看
templates/upload-api-basic.ts
用户上传完整流程请查看
references/direct-upload-complete-workflow.md

Feature 2: Image Transformations

功能2:图片转换

Optimize ANY image (uploaded or external).
Methods:
  1. URL:
    /cdn-cgi/image/width=800,quality=85/path/to/image.jpg
  2. Workers:
    cf.image
    fetch option
Load
references/transformation-options.md
for all options.
Load
templates/transform-via-workers.ts
for Workers example.
优化任意图片(已上传或外部图片)
实现方式
  1. URL方式:
    /cdn-cgi/image/width=800,quality=85/path/to/image.jpg
  2. Workers方式:
    cf.image
    请求选项
所有转换选项请查看
references/transformation-options.md
Workers转换示例请查看
templates/transform-via-workers.ts

Feature 3: Variants

功能3:图片变体

Predefined transformations (up to 100).
Examples:
  • thumbnail
    : 200x200, fit=cover
  • hero
    : 1920x1080, quality=90
  • mobile
    : 640, quality=75
Load
references/variants-guide.md
for complete guide.

预定义转换规则(最多支持100种)
示例
  • thumbnail
    :200x200,fit=cover
  • hero
    :1920x1080,quality=90
  • mobile
    :640,quality=75
完整指南请查看
references/variants-guide.md

Critical Rules

关键规则

Always Do ✅

必须遵循 ✅

  1. Use multipart/form-data for uploads (not JSON)
  2. Enable transformations for zones before using
    /cdn-cgi/image/
  3. Use direct creator upload for user uploads (don't expose API tokens)
  4. Set CORS headers for direct uploads from browser
  5. Use signed URLs for private images
  6. Configure variants for common sizes (avoid dynamic transformations)
  7. Use format=auto for automatic WebP/AVIF
  8. Handle error codes (9401, 9403, 9413, 5408)
  9. Set quality=85 for optimal size/quality balance
  10. Use fit=cover for consistent aspect ratios
  1. 上传时使用multipart/form-data格式(而非JSON)
  2. 在使用
    /cdn-cgi/image/
    前,为域名启用转换功能
  3. 用户上传场景使用直接创作者上传(不要暴露API令牌)
  4. 为浏览器端直接上传配置CORS头
  5. 为私有图片使用签名URL
  6. 为常用尺寸配置图片变体(避免动态转换)
  7. 使用format=auto自动切换WebP/AVIF格式
  8. 处理错误码(9401、9403、9413、5408)
  9. 设置quality=85以平衡图片大小与质量
  10. 使用fit=cover保证一致的宽高比

Never Do ❌

禁止操作 ❌

  1. Never expose API tokens in frontend code
  2. Never use JSON encoding for file uploads
  3. Never skip CORS configuration for direct uploads
  4. Never exceed 100 variants (hard limit)
  5. Never use transformations without enabling for zone
  6. Never hardcode account IDs in public code
  7. Never skip error handling (uploads can fail)
  8. Never use quality >90 (diminishing returns)
  9. Never skip image validation (size, format, dimensions)
  10. Never use transformations on non-proxied requests

  1. 绝对不要在前端代码中暴露API令牌
  2. 绝对不要使用JSON编码上传文件
  3. 绝对不要跳过直接上传的CORS配置
  4. 绝对不要超过100种图片变体(硬性限制)
  5. 绝对不要在未启用域名转换的情况下使用转换功能
  6. 绝对不要在公开代码中硬编码账户ID
  7. 绝对不要跳过错误处理(上传可能失败)
  8. 绝对不要将quality设置为90以上(收益递减)
  9. 绝对不要跳过图片验证(大小、格式、尺寸)
  10. 绝对不要在非代理请求上使用转换功能

Top 2 Use Cases

两大核心使用场景

Use Case 1: User Profile Pictures

场景1:用户头像上传

Direct creator upload pattern for user-uploaded images:
typescript
// Backend: Generate upload URL
const response = await fetch(
  `https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/images/v2/direct_upload`,
  { method: 'POST', headers: { 'Authorization': `Bearer ${API_TOKEN}` } }
);
const { result } = await response.json();
return Response.json({ uploadURL: result.uploadURL });

// Frontend: Upload file
const formData = new FormData();
formData.append('file', file);
await fetch(uploadURL, { method: 'POST', body: formData });
Load
templates/direct-creator-upload-backend.ts
for complete example.
See
examples/basic-upload/
for complete working project.
用户上传图片的直接创作者上传模式:
typescript
// 后端:生成上传URL
const response = await fetch(
  `https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/images/v2/direct_upload`,
  { method: 'POST', headers: { 'Authorization': `Bearer ${API_TOKEN}` } }
);
const { result } = await response.json();
return Response.json({ uploadURL: result.uploadURL });

// 前端:上传文件
const formData = new FormData();
formData.append('file', file);
await fetch(uploadURL, { method: 'POST', body: formData });
完整示例请查看
templates/direct-creator-upload-backend.ts
完整项目示例请查看
examples/basic-upload/

Use Case 2: Responsive Images

场景2:响应式图片

Responsive images with srcset for optimal performance:
html
<img
  srcset="
    https://imagedelivery.net/abc/xyz/width=400 400w,
    https://imagedelivery.net/abc/xyz/width=800 800w,
    https://imagedelivery.net/abc/xyz/width=1200 1200w
  "
  sizes="(max-width: 600px) 400px, (max-width: 1000px) 800px, 1200px"
  src="https://imagedelivery.net/abc/xyz/width=800"
/>
Load
templates/responsive-images-srcset.html
for complete example.
See
examples/responsive-gallery/
for complete working project.
Additional Use Cases:
  • Transform Existing Images: Load
    references/transformation-options.md
  • Private Images: Load
    references/signed-urls-guide.md
    or see
    examples/private-images/
  • Batch Upload: Load
    templates/batch-upload.ts
  • Framework Integration: Load
    references/framework-integration.md
    for Next.js, Remix, Astro
  • Watermarking: Load
    references/overlays-watermarks.md
    and
    templates/overlay-watermark.ts
  • Custom Domains: Load
    references/custom-domains.md
  • Webhooks: Load
    references/webhooks-guide.md
    and
    templates/webhook-handler.ts

使用srcset实现高性能响应式图片:
html
<img
  srcset="
    https://imagedelivery.net/abc/xyz/width=400 400w,
    https://imagedelivery.net/abc/xyz/width=800 800w,
    https://imagedelivery.net/abc/xyz/width=1200 1200w
  "
  sizes="(max-width: 600px) 400px, (max-width: 1000px) 800px, 1200px"
  src="https://imagedelivery.net/abc/xyz/width=800"
/>
完整示例请查看
templates/responsive-images-srcset.html
完整项目示例请查看
examples/responsive-gallery/
其他使用场景
  • 转换现有图片:查看
    references/transformation-options.md
  • 私有图片:查看
    references/signed-urls-guide.md
    examples/private-images/
  • 批量上传:查看
    templates/batch-upload.ts
  • 框架集成:查看
    references/framework-integration.md
    获取Next.js、Remix、Astro相关指南
  • 水印添加:查看
    references/overlays-watermarks.md
    templates/overlay-watermark.ts
  • 自定义域名:查看
    references/custom-domains.md
  • Webhooks:查看
    references/webhooks-guide.md
    templates/webhook-handler.ts

Top 2 Errors Prevented

两大常见错误预防

Error 1: CORS Issues with Direct Upload

错误1:直接上传的CORS问题

Problem: Browser blocks direct upload from your domain.
Solution: Configure CORS headers when generating upload URL:
typescript
const response = await fetch(
  `https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/images/v2/direct_upload`,
  {
    method: 'POST',
    headers: { 'Authorization': `Bearer ${API_TOKEN}` },
    body: JSON.stringify({
      requireSignedURLs: false,
      metadata: { source: 'user-upload' }
    })
  }
);
问题:浏览器阻止从你的域名发起直接上传请求
解决方案:生成上传URL时配置CORS头:
typescript
const response = await fetch(
  `https://api.cloudflare.com/client/v4/accounts/${ACCOUNT_ID}/images/v2/direct_upload`,
  {
    method: 'POST',
    headers: { 'Authorization': `Bearer ${API_TOKEN}` },
    body: JSON.stringify({
      requireSignedURLs: false,
      metadata: { source: 'user-upload' }
    })
  }
);

Error 2: Multipart Form Data Encoding

错误2:多部分表单数据编码问题

Problem: JSON encoding fails for file uploads (must use multipart/form-data).
Solution:
typescript
// ✅ CORRECT
const formData = new FormData();
formData.append('file', file);
await fetch(uploadURL, { method: 'POST', body: formData });

// ❌ WRONG
const json = JSON.stringify({ file: base64File });
Additional Common Errors:
  • Error 9401 (Transformations not enabled): Load
    references/top-errors.md
  • Error 9403 (Invalid transformation): Load
    references/top-errors.md
  • Error 9413 (Variant limit exceeded): Load
    references/top-errors.md
  • Error 5408 (Upload timeout): Load
    references/top-errors.md
  • Missing requireSignedURLs: Load
    references/signed-urls-guide.md
Load
references/top-errors.md
for all 10 errors with complete solutions.

问题:使用JSON编码上传文件失败(必须使用multipart/form-data)
解决方案
typescript
// ✅ 正确方式
const formData = new FormData();
formData.append('file', file);
await fetch(uploadURL, { method: 'POST', body: formData });

// ❌ 错误方式
const json = JSON.stringify({ file: base64File });
其他常见错误
  • 错误9401(未启用转换功能):查看
    references/top-errors.md
  • 错误9403(无效转换规则):查看
    references/top-errors.md
  • 错误9413(超过变体数量限制):查看
    references/top-errors.md
  • 错误5408(上传超时):查看
    references/top-errors.md
  • 缺少requireSignedURLs配置:查看
    references/signed-urls-guide.md
所有10种错误及完整解决方案请查看
references/top-errors.md

When to Load References

何时查看参考文档

Core References

核心参考文档

Load
references/setup-guide.md
when:
  • First-time Cloudflare Images setup
  • Need step-by-step walkthrough
Load
references/api-reference.md
when:
  • Need complete API documentation
  • All endpoints and parameters
Load
references/top-errors.md
when:
  • Encountering any error code (5408, 9401-9413)
  • Troubleshooting upload/transformation issues
当以下情况时查看
references/setup-guide.md
  • 首次配置Cloudflare Images
  • 需要分步操作指南
当以下情况时查看
references/api-reference.md
  • 需要完整的API文档
  • 查询所有端点及参数
当以下情况时查看
references/top-errors.md
  • 遇到任意错误码(5408、9401-9413)
  • 排查上传/转换问题

Upload References

上传相关参考文档

Load
references/direct-upload-complete-workflow.md
when:
  • Implementing user uploads
  • Need frontend + backend example
  • Configuring CORS
Load
references/signed-urls-guide.md
when:
  • Implementing private images with access control
  • Need HMAC-SHA256 signature generation
Load
references/webhooks-guide.md
when:
  • Processing upload completion events
  • Implementing webhook handlers with signature verification
当以下情况时查看
references/direct-upload-complete-workflow.md
  • 实现用户上传功能
  • 需要前后端完整示例
  • 配置CORS
当以下情况时查看
references/signed-urls-guide.md
  • 实现带访问控制的私有图片功能
  • 需要生成HMAC-SHA256签名
当以下情况时查看
references/webhooks-guide.md
  • 处理上传完成事件
  • 实现带签名验证的Webhook处理器

Transformation References

转换相关参考文档

Load
references/transformation-options.md
when:
  • Need complete transformation reference
  • Exploring all fit/format/effect options
Load
references/format-optimization.md
when:
  • Optimizing format selection (WebP/AVIF)
  • Quality vs size tradeoffs
Load
references/polish-compression.md
when:
  • Need details on Lossless/Lossy/WebP compression modes
  • Metadata handling (EXIF removal)
Load
references/overlays-watermarks.md
when:
  • Adding text or logo watermarks
  • Implementing branding/copyright protection
当以下情况时查看
references/transformation-options.md
  • 需要完整的转换规则参考
  • 探索所有fit/format/effect选项
当以下情况时查看
references/format-optimization.md
  • 优化格式选择(WebP/AVIF)
  • 权衡质量与大小
当以下情况时查看
references/polish-compression.md
  • 需要了解无损/有损/WebP压缩模式细节
  • 处理元数据(移除EXIF)
当以下情况时查看
references/overlays-watermarks.md
  • 添加文字或Logo水印
  • 实现品牌标识/版权保护

Advanced Features

高级功能参考文档

Load
references/variants-guide.md
when:
  • Creating/managing variants (up to 100 max)
  • Need flexible variants vs named variants
Load
references/responsive-images-patterns.md
when:
  • Building responsive images with srcset
  • Implementing picture element for art direction
Load
references/framework-integration.md
when:
  • Integrating with Next.js, Remix, Astro, SvelteKit
  • Need framework-specific patterns and loaders
Load
references/custom-domains.md
when:
  • Serving images from branded domains
  • CNAME configuration and SSL setup
Load
references/content-credentials.md
when:
  • Preserving EXIF/IPTC metadata
  • Implementing C2PA Content Credentials for authenticity
Load
references/sourcing-kit.md
when:
  • Migrating from Cloudinary, Imgix, or S3
  • Bulk import from external CDNs

当以下情况时查看
references/variants-guide.md
  • 创建/管理图片变体(最多100种)
  • 对比灵活变体与命名变体
当以下情况时查看
references/responsive-images-patterns.md
  • 使用srcset构建响应式图片
  • 实现picture元素进行艺术方向控制
当以下情况时查看
references/framework-integration.md
  • 与Next.js、Remix、Astro、SvelteKit集成
  • 需要框架特定的模式与加载器
当以下情况时查看
references/custom-domains.md
  • 使用品牌域名分发图片
  • 配置CNAME与SSL
当以下情况时查看
references/content-credentials.md
  • 保留EXIF/IPTC元数据
  • 实现C2PA内容凭证以确保真实性
当以下情况时查看
references/sourcing-kit.md
  • 从Cloudinary、Imgix或S3迁移
  • 从外部CDN批量导入

Using Bundled Resources

使用捆绑资源

References (16 reference files)

参考文档(16个文件)

Core: setup-guide.md, api-reference.md, top-errors.md
Upload: direct-upload-complete-workflow.md, signed-urls-guide.md, webhooks-guide.md
Transform: transformation-options.md, format-optimization.md, polish-compression.md, overlays-watermarks.md
Advanced: variants-guide.md, responsive-images-patterns.md, framework-integration.md, custom-domains.md, content-credentials.md, sourcing-kit.md
核心:setup-guide.md、api-reference.md、top-errors.md
上传:direct-upload-complete-workflow.md、signed-urls-guide.md、webhooks-guide.md
转换:transformation-options.md、format-optimization.md、polish-compression.md、overlays-watermarks.md
高级:variants-guide.md、responsive-images-patterns.md、framework-integration.md、custom-domains.md、content-credentials.md、sourcing-kit.md

Templates (16 template files)

模板文件(16个)

Upload: upload-api-basic.ts, upload-via-url.ts, direct-creator-upload-backend.ts, direct-creator-upload-frontend.html, batch-upload.ts
Transform: transform-via-url.ts, transform-via-workers.ts, overlay-watermark.ts
Variants: variants-management.ts, signed-urls-generation.ts, responsive-images-srcset.html
Integration: nextjs-integration.tsx, remix-integration.tsx, webhook-handler.ts
Config: wrangler-images-binding.jsonc, package.json
上传:upload-api-basic.ts、upload-via-url.ts、direct-creator-upload-backend.ts、direct-creator-upload-frontend.html、batch-upload.ts
转换:transform-via-url.ts、transform-via-workers.ts、overlay-watermark.ts
变体:variants-management.ts、signed-urls-generation.ts、responsive-images-srcset.html
集成:nextjs-integration.tsx、remix-integration.tsx、webhook-handler.ts
配置:wrangler-images-binding.jsonc、package.json

Agents (3 autonomous agents)

自主Agent(3个)

  • troubleshooting-agent - Diagnose upload/transformation errors (5408, 9401-9413)
  • upload-workflow-agent - Guide complete upload implementation (frontend + backend)
  • optimization-agent - Recommend image optimization strategies
Use:
/agent <agent-name>
or let Claude auto-detect when relevant
  • troubleshooting-agent - 诊断上传/转换错误(5408、9401-9413)
  • upload-workflow-agent - 指导完整上传流程实现(前后端)
  • optimization-agent - 推荐图片优化策略
使用方式:
/agent <agent-name>
,或由Claude自动识别触发

Commands (3 slash commands)

斜杠命令(3个)

  • /check-images - Quick API health check and configuration validation
  • /validate-config - Validate wrangler.jsonc bindings and configuration
  • /generate-variant - Interactive variant generator
Use:
/<command-name>
  • /check-images - 快速API健康检查与配置验证
  • /validate-config - 验证wrangler.jsonc绑定与配置
  • /generate-variant - 交互式变体生成器
使用方式:
/<command-name>

Examples (3 complete working projects)

示例项目(3个完整可运行项目)

  • basic-upload/ - Minimal upload implementation with Hono + Workers
  • responsive-gallery/ - Responsive image gallery with srcset and lazy loading
  • private-images/ - Signed URLs with time-based expiry and access control
Clone and run:
cd examples/<example-name> && npm install && npm run dev
  • basic-upload/ - 基于Hono + Workers的极简上传实现
  • responsive-gallery/ - 带srcset与懒加载的响应式图片画廊
  • private-images/ - 带时间过期与访问控制的签名URL实现
克隆并运行:
cd examples/<example-name> && npm install && npm run dev

Architecture Diagrams (3 diagrams)

架构图(3个)

  • direct-upload-workflow.md - Sequence diagram of direct creator upload flow
  • transformation-pipeline.md - Flowchart showing transformation processing
  • variants-structure.md - Named vs flexible variants comparison
View in:
assets/diagrams/
  • direct-upload-workflow.md - 直接创作者上传流程的序列图
  • transformation-pipeline.md - 转换处理流程图
  • variants-structure.md - 命名变体与灵活变体对比图
查看路径:
assets/diagrams/

Utility Scripts (5 scripts)

工具脚本(5个)

  • test-upload.sh - Test API connectivity with sample image upload
  • generate-signed-url.sh - CLI tool to generate signed URLs with expiry
  • validate-variants.sh - List all variants and check variant count (max 100)
  • analyze-usage.sh - Query API for storage usage and estimated costs
  • check-versions.sh - Verify package versions are current
Run:
./scripts/<script-name>.sh
(requires CF_ACCOUNT_ID and CF_API_TOKEN in .env)

  • test-upload.sh - 测试API连通性与示例图片上传
  • generate-signed-url.sh - 生成带过期时间的签名URL的CLI工具
  • validate-variants.sh - 列出所有变体并检查数量(最多100种)
  • analyze-usage.sh - 查询API存储使用情况与预估成本
  • check-versions.sh - 验证包版本是否为最新
运行方式:
./scripts/<script-name>.sh
(需在.env中配置CF_ACCOUNT_ID与CF_API_TOKEN)

Pricing

定价

Images API: $5/100k stored, $1/100k delivered Transformations: $0.50/1k (100k/month free per zone) Direct Upload: Included in API pricing

Images API:5美元/10万张存储图片,1美元/10万张分发图片 转换功能:0.5美元/1000次转换(每个域名每月免费10万次) 直接创作者上传:包含在API定价中

Official Documentation

官方文档