cloudflare-images
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCloudflare 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:
- Images API: Upload, store, serve images globally
- 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
它包含两大核心功能:
- Images API:在全球范围内上传、存储、分发图片
- 图片转换:调整大小/优化任意图片
核心优势:
- 全球CDN分发
- 自动转换为WebP/AVIF格式
- 支持最多100种图片变体
- 直接创作者上传(前端无需暴露API密钥)
- 为私有图片生成签名URL
- 通过URL或Workers转换任意图片
Quick Start (5 Minutes)
快速入门(5分钟)
1. Enable Cloudflare Images
1. 启用Cloudflare Images
Dashboard → Images → Enable
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 , not JSON
multipart/form-databash
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'重要提示:请使用格式,而非JSON
multipart/form-data3. 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 → Images → Transformations → Enable 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 for complete walkthrough.
references/setup-guide.mdtypescript
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.mdThe 3 Core Features
三大核心功能
Feature 1: Images API (Upload & Storage)
功能1:Images API(上传与存储)
Upload methods:
- File upload (server-side)
- Upload via URL (ingest from external)
- Direct creator upload (user uploads, no API keys)
Load for file upload example.
Load for user uploads.
templates/upload-api-basic.tsreferences/direct-upload-complete-workflow.md上传方式:
- 文件上传(服务端)
- 通过URL上传(从外部导入)
- 直接创作者上传(用户自主上传,无需暴露API密钥)
文件上传示例请查看
用户上传完整流程请查看
templates/upload-api-basic.tsreferences/direct-upload-complete-workflow.mdFeature 2: Image Transformations
功能2:图片转换
Optimize ANY image (uploaded or external).
Methods:
- URL:
/cdn-cgi/image/width=800,quality=85/path/to/image.jpg - Workers: fetch option
cf.image
Load for all options.
Load for Workers example.
references/transformation-options.mdtemplates/transform-via-workers.ts优化任意图片(已上传或外部图片)
实现方式:
- URL方式:
/cdn-cgi/image/width=800,quality=85/path/to/image.jpg - Workers方式:请求选项
cf.image
所有转换选项请查看
Workers转换示例请查看
references/transformation-options.mdtemplates/transform-via-workers.tsFeature 3: Variants
功能3:图片变体
Predefined transformations (up to 100).
Examples:
- : 200x200, fit=cover
thumbnail - : 1920x1080, quality=90
hero - : 640, quality=75
mobile
Load for complete guide.
references/variants-guide.md预定义转换规则(最多支持100种)
示例:
- :200x200,fit=cover
thumbnail - :1920x1080,quality=90
hero - :640,quality=75
mobile
完整指南请查看
references/variants-guide.mdCritical Rules
关键规则
Always Do ✅
必须遵循 ✅
- Use multipart/form-data for uploads (not JSON)
- Enable transformations for zones before using
/cdn-cgi/image/ - Use direct creator upload for user uploads (don't expose API tokens)
- Set CORS headers for direct uploads from browser
- Use signed URLs for private images
- Configure variants for common sizes (avoid dynamic transformations)
- Use format=auto for automatic WebP/AVIF
- Handle error codes (9401, 9403, 9413, 5408)
- Set quality=85 for optimal size/quality balance
- Use fit=cover for consistent aspect ratios
- 上传时使用multipart/form-data格式(而非JSON)
- 在使用前,为域名启用转换功能
/cdn-cgi/image/ - 用户上传场景使用直接创作者上传(不要暴露API令牌)
- 为浏览器端直接上传配置CORS头
- 为私有图片使用签名URL
- 为常用尺寸配置图片变体(避免动态转换)
- 使用format=auto自动切换WebP/AVIF格式
- 处理错误码(9401、9403、9413、5408)
- 设置quality=85以平衡图片大小与质量
- 使用fit=cover保证一致的宽高比
Never Do ❌
禁止操作 ❌
- Never expose API tokens in frontend code
- Never use JSON encoding for file uploads
- Never skip CORS configuration for direct uploads
- Never exceed 100 variants (hard limit)
- Never use transformations without enabling for zone
- Never hardcode account IDs in public code
- Never skip error handling (uploads can fail)
- Never use quality >90 (diminishing returns)
- Never skip image validation (size, format, dimensions)
- Never use transformations on non-proxied requests
- 绝对不要在前端代码中暴露API令牌
- 绝对不要使用JSON编码上传文件
- 绝对不要跳过直接上传的CORS配置
- 绝对不要超过100种图片变体(硬性限制)
- 绝对不要在未启用域名转换的情况下使用转换功能
- 绝对不要在公开代码中硬编码账户ID
- 绝对不要跳过错误处理(上传可能失败)
- 绝对不要将quality设置为90以上(收益递减)
- 绝对不要跳过图片验证(大小、格式、尺寸)
- 绝对不要在非代理请求上使用转换功能
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 for complete example.
See for complete working project.
templates/direct-creator-upload-backend.tsexamples/basic-upload/用户上传图片的直接创作者上传模式:
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.tsexamples/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 for complete example.
See for complete working project.
templates/responsive-images-srcset.htmlexamples/responsive-gallery/Additional Use Cases:
- Transform Existing Images: Load
references/transformation-options.md - Private Images: Load or see
references/signed-urls-guide.mdexamples/private-images/ - Batch Upload: Load
templates/batch-upload.ts - Framework Integration: Load for Next.js, Remix, Astro
references/framework-integration.md - Watermarking: Load and
references/overlays-watermarks.mdtemplates/overlay-watermark.ts - Custom Domains: Load
references/custom-domains.md - Webhooks: Load and
references/webhooks-guide.mdtemplates/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.htmlexamples/responsive-gallery/其他使用场景:
- 转换现有图片:查看
references/transformation-options.md - 私有图片:查看或
references/signed-urls-guide.mdexamples/private-images/ - 批量上传:查看
templates/batch-upload.ts - 框架集成:查看获取Next.js、Remix、Astro相关指南
references/framework-integration.md - 水印添加:查看和
references/overlays-watermarks.mdtemplates/overlay-watermark.ts - 自定义域名:查看
references/custom-domains.md - Webhooks:查看和
references/webhooks-guide.mdtemplates/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 for all 10 errors with complete solutions.
references/top-errors.md问题:使用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.mdWhen to Load References
何时查看参考文档
Core References
核心参考文档
Load when:
references/setup-guide.md- First-time Cloudflare Images setup
- Need step-by-step walkthrough
Load when:
references/api-reference.md- Need complete API documentation
- All endpoints and parameters
Load when:
references/top-errors.md- 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 when:
references/direct-upload-complete-workflow.md- Implementing user uploads
- Need frontend + backend example
- Configuring CORS
Load when:
references/signed-urls-guide.md- Implementing private images with access control
- Need HMAC-SHA256 signature generation
Load when:
references/webhooks-guide.md- 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 when:
references/transformation-options.md- Need complete transformation reference
- Exploring all fit/format/effect options
Load when:
references/format-optimization.md- Optimizing format selection (WebP/AVIF)
- Quality vs size tradeoffs
Load when:
references/polish-compression.md- Need details on Lossless/Lossy/WebP compression modes
- Metadata handling (EXIF removal)
Load when:
references/overlays-watermarks.md- 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 when:
references/variants-guide.md- Creating/managing variants (up to 100 max)
- Need flexible variants vs named variants
Load when:
references/responsive-images-patterns.md- Building responsive images with srcset
- Implementing picture element for art direction
Load when:
references/framework-integration.md- Integrating with Next.js, Remix, Astro, SvelteKit
- Need framework-specific patterns and loaders
Load when:
references/custom-domains.md- Serving images from branded domains
- CNAME configuration and SSL setup
Load when:
references/content-credentials.md- Preserving EXIF/IPTC metadata
- Implementing C2PA Content Credentials for authenticity
Load when:
references/sourcing-kit.md- 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: or let Claude auto-detect when relevant
/agent <agent-name>- troubleshooting-agent - 诊断上传/转换错误(5408、9401-9413)
- upload-workflow-agent - 指导完整上传流程实现(前后端)
- optimization-agent - 推荐图片优化策略
使用方式:,或由Claude自动识别触发
/agent <agent-name>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 devArchitecture 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: (requires CF_ACCOUNT_ID and CF_API_TOKEN in .env)
./scripts/<script-name>.sh- test-upload.sh - 测试API连通性与示例图片上传
- generate-signed-url.sh - 生成带过期时间的签名URL的CLI工具
- validate-variants.sh - 列出所有变体并检查数量(最多100种)
- analyze-usage.sh - 查询API存储使用情况与预估成本
- check-versions.sh - 验证包版本是否为最新
运行方式:(需在.env中配置CF_ACCOUNT_ID与CF_API_TOKEN)
./scripts/<script-name>.shPricing
定价
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
官方文档
- Images Overview: https://developers.cloudflare.com/images/
- Upload API: https://developers.cloudflare.com/images/upload-images/
- Transformations: https://developers.cloudflare.com/images/transform-images/
- Direct Creator Upload: https://developers.cloudflare.com/images/upload-images/direct-creator-upload/
- Variants: https://developers.cloudflare.com/images/manage-images/create-variants/
- Images概览:https://developers.cloudflare.com/images/
- 上传API:https://developers.cloudflare.com/images/upload-images/
- 转换功能:https://developers.cloudflare.com/images/transform-images/
- 直接创作者上传:https://developers.cloudflare.com/images/upload-images/direct-creator-upload/
- 图片变体:https://developers.cloudflare.com/images/manage-images/create-variants/