[ PROMPT_NODE_24130 ]
Images 配置说明
[ SKILL_DOCUMENTATION ]
# 配置
## Wrangler 集成
### Workers 绑定设置
添加到 `wrangler.toml`:
toml
name = "my-image-worker"
main = "src/index.ts"
compatibility_date = "2024-01-01"
[images]
binding = "IMAGES"
在 Worker 中访问:
typescript
interface Env {
IMAGES: ImageBinding;
}
export default {
async fetch(request: Request, env: Env): Promise {
return await env.IMAGES
.input(imageBuffer)
.transform({ width: 800 })
.output()
.response();
}
};
### 通过脚本上传
Wrangler 没有内置的 Images 命令,请使用 REST API:
typescript
// scripts/upload-image.ts
import fs from 'fs';
import FormData from 'form-data';
async function uploadImage(filePath: string) {
const accountId = process.env.CLOUDFLARE_ACCOUNT_ID!;
const apiToken = process.env.CLOUDFLARE_API_TOKEN!;
const formData = new FormData();
formData.append('file', fs.createReadStream(filePath));
const response = await fetch(
`https://api.cloudflare.com/client/v4/accounts/${accountId}/images/v1`,
{
method: 'POST',
headers: {
'Authorization': `Bearer ${apiToken}`,
},
body: formData,
}
);
const result = await response.json();
console.log('已上传:', result);
}
uploadImage('./photo.jpg');
### 环境变量
存储账户哈希以构建 URL:
toml
[vars]
IMAGES_ACCOUNT_HASH = "your-account-hash"
ACCOUNT_ID = "your-account-id"
在 Worker 中访问:
typescript
const imageUrl = `https://imagedelivery.net/${env.IMAGES_ACCOUNT_HASH}/${imageId}/public`;
## 变体配置
变体是用于转换的命名预设。
### 创建变体 (仪表板)
1. 导航至 Images → Variants
2. 点击 "Create Variant"
3. 设置名称 (例如 `thumbnail`)
4. 配置:`width=200,height=200,fit=cover`
### 创建变体 (API)
bash
curl -X POST
https://api.cloudflare.com/client/v4/accounts/{account_id}/images/v1/variants
-H "Authorization: Bearer {api_token}"
-H "Content-Type: application/json"
-d '{
"id": "thumbnail",
"options": {
"width": 200,
"height": 200,
"fit": "cover"
},
"neverRequireSignedURLs": true
}'
### 使用变体
https://imagedelivery.net/{account_hash}/{image_id}/thumbnail
### 常见变体预设
{
"thumbnail": {
"width": 200,
"height": 200,
"fit": "cover"
},
"avatar": {
"width": 128,
"height": 128,
"fit": "cover",
"gra