图片生成
本指南介绍图片生成的调用流程与常见用法。每个参数的取值、上限和错误码请查阅 API 参考。
1. 准备密钥
在控制台创建 API Key,确认它可以调用目标模型,并把它保存在服务端。下方示例从环境变量读取地址和密钥。
export IMAGE_API_BASE="https://ling-light.com"
export IMAGE_API_KEY="sk-your-api-key"2. 选择模型与接口
图片模型分为 GPT Image 和 Seedream 两个系列,它们的参考图用法不同。先按需求找到对应的接口:
| 需求 | GPT Image | Seedream |
|---|---|---|
| 文生图 | POST /v1/images/generations | POST /v1/images/generations |
| 使用参考图 | POST /v1/images/edits,参考图放在 images | POST /v1/images/generations,参考图放在 image |
| 耗时较长或需要安全重试 | POST /v1/images/tasks | POST /v1/images/tasks |
GPT Image 参数
尺寸、张数与返回格式。
Seedream 参数
分辨率档位、参考图、背景、格式与水印。
模型列表与价格
确认模型名称与计费方式。
3. 生成图片
同步接口在一次 HTTP 请求中生成并返回图片,不需要轮询。生成可能需要几十秒到数分钟,示例把客户端超时设为 240 秒;请不要在超时后自动重发,否则可能重复扣费。
GPT Image 文生图
curl --fail-with-body --max-time 240 \
--request POST "$IMAGE_API_BASE/v1/images/generations" \
--header "Authorization: Bearer $IMAGE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
"model": "gpt-image-2.6",
"n": 1,
"prompt": "生成一张横版水彩插画,主体是一只坐着的橘猫,光线柔和,画面中不要出现文字。",
"size": "1536x1024"
}' \
--output image-response.jsonimport { writeFile } from 'node:fs/promises'
const baseUrl = process.env.IMAGE_API_BASE
const apiKey = process.env.IMAGE_API_KEY
if (!baseUrl || !apiKey) throw new Error('Set IMAGE_API_BASE and IMAGE_API_KEY first')
const response = await fetch(new URL('/v1/images/generations', baseUrl), {
method: 'POST',
redirect: 'error',
signal: AbortSignal.timeout(240_000),
headers: {
Authorization: `Bearer ${apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
"model": "gpt-image-2.6",
"n": 1,
"prompt": "生成一张横版水彩插画,主体是一只坐着的橘猫,光线柔和,画面中不要出现文字。",
"size": "1536x1024"
}),
})
const result = await response.json().catch(() => null)
const rayId = response.headers.get('cf-ray')
const status = 'HTTP ' + response.status + (rayId ? ' · CF-Ray ' + rayId : '')
if (!response.ok || result?.error) {
const fallback = response.status === 524
? 'Cloudflare timed out waiting for the origin. Check usage logs before retrying.'
: "Image generation failed"
throw new Error(status + ' · ' + (result?.error?.message || result?.message || fallback))
}
if (!result) throw new Error(status + ' · Expected a JSON response')
const image = result.data?.[0]
if (!image?.url && !image?.b64_json) throw new Error('No image data returned; inspect the response')
await writeFile('image-response.json', JSON.stringify(result, null, 2))
console.log(image.url || 'Saved base64 image data in image-response.json')Seedream 参考图生成
把 image 中的地址换成可公开访问的 HTTPS 图片,或素材库中的 asset://<素材ID>。
curl --fail-with-body --max-time 240 \
--request POST "$IMAGE_API_BASE/v1/images/generations" \
--header "Authorization: Bearer $IMAGE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
"model": "seedream-5.5",
"prompt": "保留参考图中的花瓶与花枝,生成一张 9:16 的竖版水彩插画,背景为不透明的浅米色。",
"image": [
"https://media.example.com/images/reference.png"
],
"size": "2K",
"n": 1,
"background": "opaque",
"output_format": "png",
"watermark": true
}' \
--output image-response.jsonimport { writeFile } from 'node:fs/promises'
const baseUrl = process.env.IMAGE_API_BASE
const apiKey = process.env.IMAGE_API_KEY
if (!baseUrl || !apiKey) throw new Error('Set IMAGE_API_BASE and IMAGE_API_KEY first')
const response = await fetch(new URL('/v1/images/generations', baseUrl), {
method: 'POST',
redirect: 'error',
signal: AbortSignal.timeout(240_000),
headers: {
Authorization: `Bearer ${apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
"model": "seedream-5.5",
"prompt": "保留参考图中的花瓶与花枝,生成一张 9:16 的竖版水彩插画,背景为不透明的浅米色。",
"image": [
"https://media.example.com/images/reference.png"
],
"size": "2K",
"n": 1,
"background": "opaque",
"output_format": "png",
"watermark": true
}),
})
const result = await response.json().catch(() => null)
const rayId = response.headers.get('cf-ray')
const status = 'HTTP ' + response.status + (rayId ? ' · CF-Ray ' + rayId : '')
if (!response.ok || result?.error) {
const fallback = response.status === 524
? 'Cloudflare timed out waiting for the origin. Check usage logs before retrying.'
: "Image generation failed"
throw new Error(status + ' · ' + (result?.error?.message || result?.message || fallback))
}
if (!result) throw new Error(status + ' · Expected a JSON response')
const image = result.data?.[0]
if (!image?.url && !image?.b64_json) throw new Error('No image data returned; inspect the response')
await writeFile('image-response.json', JSON.stringify(result, null, 2))
console.log(image.url || 'Saved base64 image data in image-response.json'){
"created": 1795446925,
"data": [
{
"url": "https://media.example.com/images/example.png",
"width": 1024,
"height": 1024
}
]
}4. GPT Image 参考图编辑
GPT Image 使用参考图时调用 POST /v1/images/edits,把参考图放在 images 数组中,并在 prompt 里写明要修改和保留的内容。Seedream 不使用此接口。
curl --fail-with-body --max-time 300 \
--request POST "$IMAGE_API_BASE/v1/images/edits" \
--header "Authorization: Bearer $IMAGE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
"model": "gpt-image-2.6",
"prompt": "保留参考图的主体和构图,将画面转换为水彩插画。",
"images": [
{
"image_url": "https://media.example.com/images/reference.png"
}
],
"n": 1,
"size": "1024x1024"
}' \
--output image-edit-result.jsonimport { writeFile } from 'node:fs/promises'
const baseUrl = process.env.IMAGE_API_BASE
const apiKey = process.env.IMAGE_API_KEY
if (!baseUrl || !apiKey) throw new Error('Set IMAGE_API_BASE and IMAGE_API_KEY first')
const response = await fetch(new URL('/v1/images/edits', baseUrl), {
method: 'POST',
redirect: 'error',
signal: AbortSignal.timeout(300_000),
headers: {
Authorization: `Bearer ${apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
"model": "gpt-image-2.6",
"prompt": "保留参考图的主体和构图,将画面转换为水彩插画。",
"images": [
{
"image_url": "https://media.example.com/images/reference.png"
}
],
"n": 1,
"size": "1024x1024"
}),
})
const result = await response.json().catch(() => null)
const rayId = response.headers.get('cf-ray')
const status = 'HTTP ' + response.status + (rayId ? ' · CF-Ray ' + rayId : '')
if (!response.ok || result?.error) {
const fallback = response.status === 524
? 'Cloudflare timed out waiting for the origin. Check usage logs before retrying.'
: "Image editing failed"
throw new Error(status + ' · ' + (result?.error?.message || result?.message || fallback))
}
if (!result) throw new Error(status + ' · Expected a JSON response')
await writeFile('image-edit-result.json', JSON.stringify(result, null, 2))
console.log(result.data?.[0]?.url || 'Saved the response in image-edit-result.json')5. 保存图片
每个 data 项对应一张图片:有 url 时下载该地址(不要附带 API Key),有 b64_json 时解码后保存。链接可能过期,请及时保存到自己的存储。
# 替换为 image-response.json 中 data[0].url 的值。
export IMAGE_URL="https://media.example.com/images/example.png"
curl --fail --location --proto '=https' --proto-redir '=https' \
--max-time 60 "$IMAGE_URL" --output image.pngimport { readFile, writeFile } from 'node:fs/promises'
const result = JSON.parse(await readFile('image-response.json', 'utf8'))
const item = result.data?.[0]
if (item?.b64_json) {
await writeFile('image.png', Buffer.from(item.b64_json, 'base64'))
} else {
if (!item?.url) throw new Error('No image in the saved response')
const response = await fetch(item.url, { signal: AbortSignal.timeout(60_000) })
if (!response.ok) throw new Error(`Image download failed: HTTP ${response.status}`)
await writeFile('image.png', Buffer.from(await response.arrayBuffer()))
}
console.log('Saved image.png')6. 异步图片任务
生成耗时较长、网络不稳定或需要安全重试时,改用 POST /v1/images/tasks。请求体与同步接口相同,另需请求头 Idempotency-Key:提交结果不明时,用同一个键和相同请求体重试会返回原任务,不会重复生成。受理后轮询 GET /v1/tasks/{id},状态为 SUCCESS 后从 GET /v1/tasks/{id}/artifacts 取图片地址(15 分钟内有效,过期可重新获取)。
# 用你的业务请求编号替换 image-order-001,重试时保持不变。
curl --fail-with-body -X POST "$IMAGE_API_BASE/v1/images/tasks" \
-H "Authorization: Bearer $IMAGE_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: image-order-001" \
-d '{"model":"gpt-image-2.6","prompt":"A cat in a garden","size":"1024x1024"}'
# 将 TASK_ID 替换为响应中的 task_id。
curl --fail-with-body "$IMAGE_API_BASE/v1/tasks/$TASK_ID" \
-H "Authorization: Bearer $IMAGE_API_KEY"
# 状态为 SUCCESS 时读取产物。
curl --fail-with-body "$IMAGE_API_BASE/v1/tasks/$TASK_ID/artifacts" \
-H "Authorization: Bearer $IMAGE_API_KEY"const base = process.env.IMAGE_API_BASE
const apiKey = process.env.IMAGE_API_KEY
const key = process.env.IMAGE_REQUEST_ID
if (!base || !apiKey || !key) throw new Error('Set IMAGE_API_BASE, IMAGE_API_KEY and IMAGE_REQUEST_ID')
const headers = { Authorization: `Bearer ${apiKey}` }
const submission = await fetch(new URL('/v1/images/tasks', base), {
method: 'POST',
headers: { ...headers, 'Content-Type': 'application/json', 'Idempotency-Key': key },
body: JSON.stringify({ model: 'gpt-image-2.6', prompt: 'A cat in a garden', size: '1024x1024' }),
})
if (!submission.ok) throw new Error(await submission.text())
const { task_id } = await submission.json()
let task
do {
await new Promise((resolve) => setTimeout(resolve, 4000))
const status = await fetch(new URL(`/v1/tasks/${task_id}`, base), { headers })
if (!status.ok) throw new Error(await status.text())
task = await status.json()
} while (task.status !== 'SUCCESS' && task.status !== 'FAILURE')
if (task.status === 'FAILURE') throw new Error(task.fail_reason || 'Image task failed')
const artifacts = await fetch(new URL(`/v1/tasks/${task_id}/artifacts`, base), { headers })
console.log(await artifacts.json())错误与重试
- 请求失败时读取 error.message,按提示修正参数、模型权限或额度;具体错误码见 API 参考。
- 同步请求超时、断连或返回 5xx(包括 Cloudflare 524 页面)时,图片可能已生成并计费。先查看使用日志,再决定是否重试。
- 需要自动重试的业务请使用异步图片任务和 Idempotency-Key。