OpenAI 图像生成 API 参考文档
数据来源:
• https://platform.openai.com/docs/api-reference/images/create • https://developers.openai.com/api/docs/guides/image-generation • https://developers.openai.com/api/docs/guides/tools-image-generation • https://developers.openai.com/api/reference/resources/images/methods/generate/ • https://developers.openai.com/api/reference/resources/images/methods/edit/ • https://developers.openai.com/api/docs/guides/images-vision • https://docs.newapi.pro/zh/docs/api/ai-model/images/openai/post-v1-images-generations 页面覆盖: 已搜索 12 个关键词组合,提取 3 个主要端点及相关模型信息
核心能力全景
洞察总结: OpenAI 的图像生成 API 经历了从 DALL-E 2 到 DALL-E 3,再到 GPT Image 系列的演进。最新的 GPT Image 2(2026年4月发布)在文本渲染、分辨率、生成速度上实现了重大突破,生成速度提升 2 倍,支持 2K 分辨率和多语言文字。API 设计遵循 RESTful 风格,提供三个核心端点:生成、编辑、变体,适用于从简单图像生成到复杂视觉内容创作的各类场景。
模型速查表
选型建议:
• 追求质量和速度:选择 GPT Image 2,支持 2K 分辨率和多语言文本 • 平衡成本与性能:选择 GPT Image 1.5 或 GPT Image 1 • 大批量低成本:选择 GPT Image 1 Mini,成本降低 80% • 需要图像变体:使用 DALL-E 2 的 variations 端点 • 需要自动提示词优化:DALL-E 3(已退役,建议迁移到 GPT Image 系列)
支持的参数规格
图像尺寸(size)
质量等级(quality)
风格(style)
响应格式(response_format)
1. 图像生成(Create Image)
来源: https://platform.openai.com/docs/api-reference/images/create
接口:
POST https://api.openai.com/v1/images/generations认证:
Authorization: Bearer <API_KEY>Content-Type:
application/json
功能说明
根据文本提示词生成一张或多张图像。支持多种模型、尺寸、质量等级和风格选项。
可视化结构
POST /v1/images/generations
{
"model": "string", // 模型 ID
"prompt": "string", // 图像描述(必填)
"n": integer, // 生成数量
"size": "string", // 图像尺寸
"quality": "string", // 质量等级
"style": "string", // 风格(仅 DALL-E 3)
"response_format": "string", // 响应格式
"user": "string" // 用户标识符
}请求参数详细说明
dall-e-2: 1-1000 字符 dall-e-3: 1-4000 字符 | |||||
DALL-E 3: 1 GPT Image: 1-8 | |||||
standard, hd (DALL-E 3) | |||||
隐含约束:
• DALL-E 3 的 n参数只能为 1,不支持批量生成• DALL-E 2 只支持方形尺寸(256x256, 512x512, 1024x1024) • quality为hd时,价格约为standard的 2 倍• 使用 b64_json格式时,响应体积较大,建议仅在必要时使用• GPT Image 2 单次最多生成 8 张图像
请求示例
curl https://api.openai.com/v1/images/generations \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-image-2",
"prompt": "A serene Japanese garden with cherry blossoms in full bloom, koi pond, stone lanterns, and a traditional wooden bridge, photorealistic style",
"n": 1,
"size": "1792x1024",
"quality": "high",
"response_format": "url"
}'{
"model":"gpt-image-2",
"prompt":"A serene Japanese garden with cherry blossoms in full bloom, koi pond, stone lanterns, and a traditional wooden bridge, photorealistic style",
"n":1,
"size":"1792x1024",
"quality":"high",
"response_format":"url"
}示例来源:依据参数构造
响应示例
{
"created":1714521600,
"data":[
{
"url":"https://oaidalleapiprodscus.blob.core.windows.net/private/org-xxx/user-xxx/img-xxx.png?st=2026-05-07T10%3A00%3A00Z&se=2026-05-07T11%3A00%3A00Z&sp=r&sv=2021-08-06&sr=b&rscd=inline&rsct=image/png&skoid=xxx&sktid=xxx&skt=2026-05-07T09%3A59%3A00Z&ske=2026-05-08T09%3A59%3A00Z&sks=b&skv=2021-08-06&sig=xxx",
"revised_prompt":"A tranquil Japanese garden during spring, featuring cherry blossom trees in full bloom with pink petals. A koi pond with colorful fish swimming beneath the surface. Traditional stone lanterns placed strategically around the garden. A classic wooden bridge arching over the pond. The scene is captured in a photorealistic style with natural lighting."
}
]
}响应字段说明
设计意图分析:
• revised_prompt字段的存在表明 OpenAI 在生成前会自动优化提示词,增加细节和安全性检查• URL 有效期仅 1 小时,鼓励用户立即下载或使用 b64_json 格式 • 响应结构使用数组,为批量生成预留了扩展性
2. 图像编辑(Edit Image)
来源: https://developers.openai.com/api/reference/resources/images/methods/edit/
接口:
POST https://api.openai.com/v1/images/edits认证:
Authorization: Bearer <API_KEY>Content-Type:
multipart/form-data
功能说明
基于原始图像和蒙版(mask),根据文本提示词对图像进行局部编辑。蒙版中的透明区域将被重新生成。
可视化结构
POST /v1/images/edits (multipart/form-data)
{
"image": File, // 原始图像文件(必填)
"mask": File, // 蒙版图像文件(可选)
"prompt": "string", // 编辑描述(必填)
"model": "string", // 模型 ID
"n": integer, // 生成数量
"size": "string", // 输出尺寸
"response_format": "string", // 响应格式
"user": "string" // 用户标识符
}请求参数详细说明
隐含约束:
• 参数格式: images 参数是数组,每个元素包含 file_id 或 image_url(二选一) • 图像数量: GPT Image 1 系列模型最多支持 16 张输入图片,dall-e-2 仅支持 1 张 • 蒙版要求: 蒙版图像必须包含 alpha 通道(透明度),与第一张输入图像尺寸相同 • 文件大小: 每张图像必须小于 50MB • prompt 描述: 应描述整个图像的最终状态,而非仅描述要编辑的部分 • 模型限制:gpt-image-2 和 DALL-E 3 不支持此 Image API 编辑端点 • 支持的模型: dall-e-2, gpt-image-1, gpt-image-1-mini, gpt-image-1.5, chatgpt-image-latest • GPT Image 2 编辑: gpt-image-2 不支持 Image API 的编辑端点,如需编辑功能请使用 Responses API • dall-e-2 限制: dall-e-2 要求图像必须是方形 PNG,小于 4MB
请求示例
多图参考编辑(GPT Image 模型):
curl -X POST "https://api.openai.com/v1/images/edits" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-F "model=gpt-image-1.5" \
-F "image[]=@body-lotion.png" \
-F "image[]=@bath-bomb.png" \
-F "image[]=@incense-kit.png" \
-F "image[]=@soap.png" \
-F 'prompt=Create a lovely gift basket with these four items in it'单图蒙版编辑(dall-e-2):
curl https://api.openai.com/v1/images/edits \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-F "image=@original.png" \
-F "mask=@mask.png" \
-F "prompt=A cozy living room with a fireplace, warm lighting, and a cat sleeping on the sofa" \
-F "model=dall-e-2" \
-F "n=1" \
-F "size=1024x1024"Python 示例(使用 file_id):
from openai import OpenAI
client = OpenAI()
# 上传图像文件
file1 = client.files.create(
file=open("image1.png", "rb"),
purpose="vision"
)
file2 = client.files.create(
file=open("image2.png", "rb"),
purpose="vision"
)
# 编辑图像
response = client.images.edit(
images=[
{"file_id": file1.id},
{"file_id": file2.id}
],
prompt="Combine these images into a single composition",
model="gpt-image-1.5",
n=1,
size="1024x1024"
)
image_url = response.data[0].url注意: 官方 Python SDK 的
images.edit()方法可能尚未更新以支持新的images数组格式。如遇到问题,请使用client.post()直接调用 API 或查看最新的 SDK 文档。
响应示例
{
"created":1714521700,
"data":[
{
"url":"https://oaidalleapiprodscus.blob.core.windows.net/private/org-xxx/user-xxx/img-xxx.png?..."
}
]
}响应字段说明
3. 图像变体生成(Create Image Variation)
来源: https://platform.openai.com/docs/api-reference/images/createVariation
接口:
POST https://api.openai.com/v1/images/variations认证:
Authorization: Bearer <API_KEY>Content-Type:
multipart/form-data
功能说明
基于原始图像生成不同风格或细节的变体图像。不需要提示词,模型会自动理解原图内容并生成变体。
可视化结构
POST /v1/images/variations (multipart/form-data)
{
"image": File, // 原始图像文件(必填)
"model": "string", // 模型 ID
"n": integer, // 生成数量
"size": "string", // 输出尺寸
"response_format": "string", // 响应格式
"user": "string" // 用户标识符
}请求参数详细说明
隐含约束:
• 原始图像必须是方形 PNG 文件 • 变体端点仅支持 dall-e-2。所有 GPT Image 模型(包括 GPT Image 2)和 dall-e-3 均不支持此端点 • 变体生成不接受提示词,完全基于原图内容 • 文件大小必须小于 4MB
请求示例
curl https://api.openai.com/v1/images/variations \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-F "image=@original.png" \
-F "model=dall-e-2" \
-F "n=3" \
-F "size=1024x1024"from openai import OpenAI
client = OpenAI()
response = client.images.create_variation(
image=open("original.png", "rb"),
model="dall-e-2",
n=3,
size="1024x1024"
)
for idx, img inenumerate(response.data):
print(f"Variation {idx+1}: {img.url}")示例来源:依据参数构造
响应示例
{
"created":1714521800,
"data":[
{
"url":"https://oaidalleapiprodscus.blob.core.windows.net/private/org-xxx/user-xxx/img-xxx-1.png?..."
},
{
"url":"https://oaidalleapiprodscus.blob.core.windows.net/private/org-xxx/user-xxx/img-xxx-2.png?..."
},
{
"url":"https://oaidalleapiprodscus.blob.core.windows.net/private/org-xxx/user-xxx/img-xxx-3.png?..."
}
]
}响应字段说明
4. GPT Image 2 图像编辑(通过 Responses API)
来源: https://developers.openai.com/api/docs/guides/tools-image-generation
接口:
POST https://api.openai.com/v1/responses认证:
Authorization: Bearer <API_KEY>Content-Type:
application/json
功能说明
gpt-image-2 不支持 Image API 的 /v1/images/edits 端点,但可以通过 Responses API(Chat Completions API)的 image_generation 工具进行图像编辑。
Responses API 的优势:
• ✅ 支持多轮对话式编辑 • ✅ 支持多图参考编辑(最多16张) • ✅ 自动高保真输入(input_fidelity: high) • ✅ 支持蒙版编辑 • ✅ 模型自动选择生成或编辑模式
可视化结构
POST /v1/responses (application/json)
{
"model": "gpt-5.5", // 主模型(必须是支持 image_generation 工具的模型)
"input": [ // 输入内容
{
"role": "user",
"content": [
{ "type": "input_text", "text": "..." },
{ "type": "input_image", "image_url": "..." },
{ "type": "input_image", "file_id": "..." }
]
}
],
"tools": [{ "type": "image_generation" }], // 启用图像生成工具
"tool_choice": "auto" // 可选:auto, required, none
}请求参数详细说明
{ "type": "image_generation" } | ||||
input 内容类型:
{ "type": "input_text", "text": "..." } | ||
{ "type": "input_image", "image_url": "https://..." } | ||
{ "type": "input_image", "image_url": "data:image/jpeg;base64,..." } | ||
{ "type": "input_image", "file_id": "file-xxx" } |
image_generation 工具参数:
重要说明:
• gpt-image-2 不支持透明背景, background: "transparent"会导致请求失败• gpt-image-2 自动使用高保真输入,无需设置 input_fidelity 参数 • 实际使用的图像生成模型是 gpt-image-2,但 model 参数必须设置为主模型(如 gpt-5.5)
请求示例
示例 1:单图编辑(使用 Base64)
const response = await openai.responses.create({
model: "gpt-5.5",
input: [
{
role: "user",
content: [
{
type: "input_text",
text: "Make this image look more realistic and add warm lighting"
},
{
type: "input_image",
image_url: `data:image/jpeg;base64,${base64Image}`
}
]
}
],
tools: [{ type: "image_generation" }]
});
const imageData = response.output
.filter((output) => output.type === "image_generation_call")
.map((output) => output.result);示例 2:多图参考编辑(最多16张)
const response = await openai.responses.create({
model: "gpt-5.5",
input: [
{
role: "user",
content: [
{
type: "input_text",
text: "Create a lovely gift basket with these four items in it"
},
{ type: "input_image", image_url: `data:image/jpeg;base64,${base64Image1}` },
{ type: "input_image", image_url: `data:image/jpeg;base64,${base64Image2}` },
{ type: "input_image", file_id: "file-xxx1" },
{ type: "input_image", file_id: "file-xxx2" }
]
}
],
tools: [{ type: "image_generation" }]
});示例 3:多轮对话式编辑
// 第一轮:生成初始图像
const response1 = await openai.responses.create({
model: "gpt-5.5",
input: "Generate an image of a gray tabby cat hugging an otter with an orange scarf",
tools: [{ type: "image_generation" }]
});
// 第二轮:基于第一轮结果继续编辑
const response2 = await openai.responses.create({
model: "gpt-5.5",
previous_response_id: response1.id,
input: "Now make it look realistic and add a sunset background",
tools: [{ type: "image_generation" }]
});示例 4:Python 完整示例
from openai import OpenAI
import base64
client = OpenAI()
# 读取图像并转换为 Base64
withopen("input_image.png", "rb") as f:
image_data = base64.b64encode(f.read()).decode('utf-8')
# 编辑图像
response = client.responses.create(
model="gpt-5.5",
input=[
{
"role": "user",
"content": [
{
"type": "input_text",
"text": "Add a beautiful sunset background to this image"
},
{
"type": "input_image",
"image_url": f"data:image/png;base64,{image_data}"
}
]
}
],
tools=[{"type": "image_generation"}]
)
# 提取生成的图像
for output in response.output:
if output.type == "image_generation_call":
result_base64 = output.result
# 保存图像
withopen("output_image.png", "wb") as f:
f.write(base64.b64decode(result_base64))
print("Image saved to output_image.png")示例 5:强制编辑模式(action: edit)
const response = await openai.responses.create({
model: "gpt-5.5",
input: [
{
role: "user",
content: [
{ type: "input_text", text: "Change the background to a beach scene" },
{ type: "input_image", file_id: "file-xxx" }
]
}
],
tools: [
{
type: "image_generation",
parameters: {
action: "edit", // 强制使用编辑模式
quality: "high",
size: "2048x2048"
}
}
]
});响应示例
{
"id":"resp_xxx",
"object":"response",
"created":1234567890,
"model":"gpt-5.5",
"output":[
{
"type":"image_generation_call",
"result":"iVBORw0KGgoAAAANSUhEUgAA...",// Base64 编码的图像
"revised_prompt":"A photorealistic image of...",
"size":"2048x2048",
"quality":"high",
"output_format":"png"
}
],
"usage":{
"input_tokens":1250,
"output_tokens":4160,
"total_tokens":5410,
"input_tokens_details":{
"text_tokens":50,
"image_tokens":1200
},
"output_tokens_details":{
"image_tokens":4160,
"text_tokens":0
}
}
}响应字段说明
Image API vs Responses API 对比
/v1/images/edits) | /v1/responses) | |
| gpt-image-2 支持 | ||
| 支持的模型 | ||
| 多轮编辑 | ||
| 输入格式 | ||
| 图像输入方式 | ||
| 最多输入图像 | ||
| 自动选择模式 | ||
| 对话上下文 | ||
| 响应格式 |
使用建议
1. 选择合适的 API: • 单次编辑 + GPT Image 1 系列:使用 Image API • 需要 gpt-image-2:必须使用 Responses API • 多轮迭代编辑:使用 Responses API 2. 优化成本: • gpt-image-2 自动使用高保真输入,输入图像 token 消耗较高 • 使用 File ID 而非 Base64 可以减少重复上传 • 使用 quality: "low"可以降低输出 token 成本3. 提示词优化: • 主模型(gpt-5.5)会自动优化提示词 • 可以在 revised_prompt字段中查看优化后的提示词• 明确描述期望的编辑效果,而非仅描述要改变的部分 4. 错误处理: • gpt-image-2 不支持透明背景,避免设置 background: "transparent"• 确保图像尺寸符合约束(最大 3840px,必须是 16 的倍数) • 处理 token 限制错误(输入图像过多或过大)
5. 流式图像生成(Streaming)
来源: https://platform.openai.com/docs/api-reference/images-streaming
接口:
POST https://api.openai.com/v1/images/generations(添加stream: true参数)认证:
Authorization: Bearer <API_KEY>Content-Type:
application/json
功能说明
通过服务器推送事件(Server-Sent Events, SSE)实时接收图像生成进度和结果。适用于需要实时反馈的场景。
请求参数详细说明
在标准生成请求的基础上,添加 stream: true 参数即可启用流式传输。
请求示例
curl https://api.openai.com/v1/images/generations \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-image-2",
"prompt": "A futuristic cityscape at sunset",
"stream": true
}'响应示例(SSE 流)
data: {"type": "progress", "progress": 0.25}
data: {"type": "progress", "progress": 0.50}
data: {"type": "progress", "progress": 0.75}
data: {"type": "complete", "created": 1714521900, "data": [{"url": "https://..."}]}
data: [DONE]设计意图分析:
• 流式传输允许客户端实时显示生成进度,提升用户体验 • 适用于生成时间较长的高质量图像(如 GPT Image 2 的 2K 分辨率) • 使用标准的 SSE 协议,易于集成到现有系统
5. 视觉理解(Vision)
来源: https://developers.openai.com/api/docs/guides/images-vision
接口:
POST https://api.openai.com/v1/chat/completions认证:
Authorization: Bearer <API_KEY>Content-Type:
application/json
功能说明
使用 GPT-4 Turbo、GPT-4o 等多模态模型分析和理解图像内容。可以回答关于图像的问题、提取文本、描述场景等。
可视化结构
POST /v1/chat/completions
{
"model": "string", // 多模态模型 ID
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "string" // 文本问题
},
{
"type": "image_url",
"image_url": {
"url": "string", // 图像 URL 或 Base64 数据
"detail": "string" // 分析细节级别
}
}
]
}
],
"max_tokens": integer
}请求参数详细说明
隐含约束:
• 图像 URL 必须可公开访问,或使用 Base64 编码 • Base64 格式必须包含 MIME 类型前缀: data:image/jpeg;base64,• 单次请求最多支持多张图像(具体数量取决于模型) • detail为high时,token 消耗更多,但分析更精确• 图像尺寸超过 2048px 会自动缩放
请求示例
curl https://api.openai.com/v1/chat/completions \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-4o",
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "What is in this image? Describe it in detail."
},
{
"type": "image_url",
"image_url": {
"url": "https://example.com/image.jpg",
"detail": "high"
}
}
]
}
],
"max_tokens": 500
}'from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "What is in this image?"},
{
"type": "image_url",
"image_url": {
"url": "https://example.com/image.jpg",
"detail": "high"
}
}
]
}
],
max_tokens=500
)
print(response.choices[0].message.content)示例来源:依据参数构造
响应示例
{
"id":"chatcmpl-xxx",
"object":"chat.completion",
"created":1714522000,
"model":"gpt-4o-2024-05-13",
"choices":[
{
"index":0,
"message":{
"role":"assistant",
"content":"This image shows a serene Japanese garden with cherry blossom trees in full bloom. The pink petals create a beautiful canopy over a traditional wooden bridge that spans across a koi pond. Stone lanterns are strategically placed around the garden, and colorful koi fish can be seen swimming in the clear water below."
},
"finish_reason":"stop"
}
],
"usage":{
"prompt_tokens":1250,
"completion_tokens":85,
"total_tokens":1335
}
}6. 工具调用中的图像生成(Tools - Image Generation)
来源: https://developers.openai.com/api/docs/guides/tools-image-generation
接口:
POST https://api.openai.com/v1/chat/completions(使用 tools 参数)认证:
Authorization: Bearer <API_KEY>Content-Type:
application/json
功能说明
在对话流程中,让模型自动决定何时调用图像生成工具。适用于聊天机器人、智能助手等需要动态生成图像的场景。
可视化结构
POST /v1/chat/completions
{
"model": "string",
"messages": [...],
"tools": [
{
"type": "function",
"function": {
"name": "generate_image",
"description": "string",
"parameters": {
"type": "object",
"properties": {
"prompt": {"type": "string"},
"size": {"type": "string"},
...
},
"required": ["prompt"]
}
}
}
],
"tool_choice": "auto"
}请求参数详细说明
请求示例
{
"model":"gpt-4o",
"messages":[
{
"role":"user",
"content":"Create an image of a sunset over the ocean"
}
],
"tools":[
{
"type":"function",
"function":{
"name":"generate_image",
"description":"Generate an image based on a text description",
"parameters":{
"type":"object",
"properties":{
"prompt":{
"type":"string",
"description":"The text description of the image to generate"
},
"size":{
"type":"string",
"enum":["1024x1024","1792x1024","1024x1792"],
"description":"The size of the generated image"
},
"quality":{
"type":"string",
"enum":["standard","hd"],
"description":"The quality of the generated image"
}
},
"required":["prompt"]
}
}
}
],
"tool_choice":"auto"
}响应示例(模型决定调用工具)
{
"id":"chatcmpl-xxx",
"object":"chat.completion",
"created":1714522100,
"model":"gpt-4o",
"choices":[
{
"index":0,
"message":{
"role":"assistant",
"content":null,
"tool_calls":[
{
"id":"call_xxx",
"type":"function",
"function":{
"name":"generate_image",
"arguments":"{\"prompt\":\"A beautiful sunset over the ocean with orange and pink hues reflecting on the water, peaceful and serene atmosphere\",\"size\":\"1792x1024\",\"quality\":\"hd\"}"
}
}
]
},
"finish_reason":"tool_calls"
}
]
}设计意图分析:
• 工具调用模式将图像生成集成到对话流程中,模型可以自主决定何时生成图像 • 模型会自动优化用户的简单请求,生成更详细的提示词 • 适用于构建智能助手、创意工具等需要多轮交互的应用
常见错误与处理
{"error": {"message": "Incorrect API key provided", "type": "invalid_request_error"}} | ||||
{"error": {"message": "Invalid value: 'gpt-image-1'. Value must be 'dall-e-2'.", "type": "invalid_request_error"}} | ||||
{"error": {"message": "Invalid image format. Must be PNG.", "type": "invalid_request_error"}} | ||||
{"error": {"message": "Image file size exceeds 4MB limit", "type": "invalid_request_error"}} | ||||
{"error": {"message": "Your request was rejected as a result of our safety system.", "type": "invalid_request_error"}} | ||||
{"error": {"message": "You didn't provide an API key.", "type": "invalid_request_error"}} | ||||
{"error": {"message": "Payload too large", "type": "invalid_request_error"}} | ||||
{"error": {"message": "Rate limit reached for requests", "type": "rate_limit_exceeded"}} | ||||
{"error": {"message": "You exceeded your current quota", "type": "insufficient_quota"}} | ||||
{"error": {"message": "The server had an error processing your request", "type": "server_error"}} | ||||
{"error": {"message": "The engine is currently overloaded", "type": "service_unavailable"}} |
错误模式总结:
• 所有错误响应都遵循统一的 JSON 格式: {"error": {"message": "...", "type": "..."}}• 400 错误通常是客户端参数问题,需要检查请求内容 • 429 错误分为速率限制和配额不足两种,处理方式不同 • 5xx 错误是服务端问题,应实现自动重试机制
速率限制与配额
速率限制层级
注意事项:
• 速率限制基于每分钟生成的图像数量(images per minute, IPM) • 批量生成(n > 1)会按实际生成的图像数量计算 • 超过限制会返回 429 错误,建议实现指数退避重试 • 可在 https://platform.openai.com/account/limits 查看当前层级
配额管理
• 预付费模式:需要预先充值,按实际使用扣费 • 配额重置:速率限制按滚动窗口计算,每分钟重置 • 监控建议:在应用中实现速率限制跟踪,避免频繁触发 429 错误
价格信息
图像生成价格(按张计费)
DALL-E 2
DALL-E 3
GPT Image 1 Mini
GPT Image 1 / 1.5
GPT Image 2
重要说明: GPT Image 2 采用 Token 计费模式,而非简单的按张计费。下表为估算价格,实际费用取决于图像尺寸、质量等级和输入图片数量。
Token 价格(官方):
• 图像输入:$8.00 / 1M tokens • 缓存图像输入:$2.00 / 1M tokens • 图像输出:$30.00 / 1M tokens • 文本输入:$5.00 / 1M tokens
估算价格(按张):
注意:
• 编辑请求需要额外计算输入图像的 token 费用 • GPT Image 2 自动使用高保真输入,编辑时输入图像 token 消耗较高 • 使用缓存可降低重复输入的成本
视觉理解价格(按 Token 计费)
高分辨率:按图块计算 | |||
高分辨率:按图块计算 | |||
高分辨率:按图块计算 |
价格说明:
• 图像生成按生成的图像数量计费,与生成时间无关 • 视觉理解按输入和输出的 token 数量计费,图像会转换为 token • 高分辨率图像(detail: high)会被分割成 512x512 的图块,每个图块 170 tokens,再加上基础 85 tokens • 价格可能随时调整,请访问 https://openai.com/api/pricing/ 获取最新价格
需要注意的关键点
提示词优化
• DALL-E 3 自动重写:DALL-E 3 会自动重写提示词以提升安全性和质量,重写后的提示词会在响应的 revised_prompt字段中返回• 详细描述:提供详细的场景、对象、颜色、情绪、风格描述,可以显著提升生成质量 • 避免模糊词汇:使用具体的描述而非模糊的形容词(如"美丽的"、"好看的") • 风格指定:明确指定艺术风格(如"photorealistic"、"oil painting"、"watercolor")
图像文件要求
• 编辑和变体端点:必须使用 PNG 格式,且图像必须是方形 • 文件大小限制:上传的图像文件不能超过 4MB • 透明度要求:编辑端点要求图像包含 alpha 通道(透明度) • 蒙版规则:蒙版图像的尺寸必须与原始图像完全一致
内容政策
• 禁止内容:暴力、色情、仇恨言论、未成年人相关内容、名人肖像、受版权保护的角色 • 自动审核:所有提示词和生成的图像都会经过自动内容审核 • 用户标识:建议使用 user参数标识终端用户,便于追踪滥用行为• 违规处理:违反内容政策的请求会被拒绝,返回 400 错误
性能优化
• URL vs Base64:优先使用 URL 格式,Base64 会增加请求体积和传输时间 • 批量生成:使用 n参数批量生成多张图像,比多次单独请求更高效• 质量选择:根据实际需求选择质量等级, low质量生成速度更快且成本更低• 缓存策略:URL 有效期仅 1 小时,需要立即下载或使用 CDN 缓存
模型选择策略
• 成本敏感型应用:使用 GPT Image 1 Mini,成本降低 80% • 需要文本渲染:使用 GPT Image 2,支持多语言文字准确渲染 • 需要高分辨率:使用 GPT Image 2,支持 2K 分辨率(最高 4K 实验性) • 需要图像变体:使用 DALL-E 2,是唯一支持变体端点的模型 • 需要编辑功能(Image API):使用 GPT Image 1 系列(支持多图编辑)或 DALL-E 2 • 需要编辑功能(Responses API):可以使用 GPT Image 2
API 集成最佳实践
• 错误处理:实现完善的错误处理和重试机制,特别是 429 和 5xx 错误 • 指数退避:遇到速率限制时,使用指数退避算法重试(如 1s、2s、4s、8s) • 超时设置:图像生成可能需要 10-60 秒,设置合理的超时时间 • 流式传输:对于高质量图像,使用流式传输提供实时进度反馈 • 监控和日志:记录所有 API 调用、错误和性能指标,便于问题排查
模型演进历史与对比
时间线
能力对比矩阵
迁移建议:
• 从 DALL-E 2 迁移:如需编辑和变体功能,迁移到 GPT Image 1 系列;如仅需生成,迁移到 GPT Image 2 • 从 DALL-E 3 迁移:直接迁移到 GPT Image 2,获得更好的性能和更多功能 • 成本优化:将非关键场景迁移到 GPT Image 1 Mini,成本降低 80%
代码示例集合
Python SDK 完整示例
from openai import OpenAI
import base64
import os
client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
# 1. 基础图像生成
defgenerate_image(prompt, model="gpt-image-2", size="1024x1024", quality="high"):
response = client.images.generate(
model=model,
prompt=prompt,
n=1,
size=size,
quality=quality,
response_format="url"
)
return response.data[0].url
# 2. 批量生成
defgenerate_multiple_images(prompt, count=3):
response = client.images.generate(
model="gpt-image-1-mini",
prompt=prompt,
n=count,
size="1024x1024",
quality="low"
)
return [img.url for img in response.data]
# 3. Base64 格式生成并保存
defgenerate_and_save_image(prompt, filename="output.png"):
response = client.images.generate(
model="gpt-image-2",
prompt=prompt,
n=1,
size="1024x1024",
response_format="b64_json"
)
image_data = base64.b64decode(response.data[0].b64_json)
withopen(filename, "wb") as f:
f.write(image_data)
print(f"Image saved to {filename}")
# 4. 图像编辑
defedit_image(image_path, mask_path, prompt):
response = client.images.edit(
image=open(image_path, "rb"),
mask=open(mask_path, "rb"),
prompt=prompt,
model="gpt-image-1.5",
n=1,
size="1024x1024"
)
return response.data[0].url
# 5. 图像变体生成
defcreate_variations(image_path, count=3):
response = client.images.create_variation(
image=open(image_path, "rb"),
model="dall-e-2",
n=count,
size="1024x1024"
)
return [img.url for img in response.data]
# 6. 视觉理解
defanalyze_image(image_url, question):
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": question},
{"type": "image_url", "image_url": {"url": image_url, "detail": "high"}}
]
}
],
max_tokens=500
)
return response.choices[0].message.content
# 7. 错误处理和重试
import time
from openai import RateLimitError, APIError
defgenerate_with_retry(prompt, max_retries=3):
for attempt inrange(max_retries):
try:
response = client.images.generate(
model="gpt-image-2",
prompt=prompt,
n=1,
size="1024x1024"
)
return response.data[0].url
except RateLimitError:
if attempt < max_retries - 1:
wait_time = 2 ** attempt # 指数退避:1s, 2s, 4s
print(f"Rate limit hit, waiting {wait_time}s...")
time.sleep(wait_time)
else:
raise
except APIError as e:
print(f"API error: {e}")
if attempt < max_retries - 1:
time.sleep(2)
else:
raise
# 使用示例
if __name__ == "__main__":
# 生成图像
url = generate_image("A futuristic city at sunset, cyberpunk style")
print(f"Generated image: {url}")
# 批量生成
urls = generate_multiple_images("A cute cat", count=3)
print(f"Generated {len(urls)} images")
# 保存为文件
generate_and_save_image("A serene mountain landscape", "mountain.png")Node.js SDK 完整示例
importOpenAIfrom'openai';
import fs from'fs';
const openai = newOpenAI({
apiKey: process.env.OPENAI_API_KEY
});
// 1. 基础图像生成
asyncfunctiongenerateImage(prompt, model = 'gpt-image-2') {
const response = await openai.images.generate({
model: model,
prompt: prompt,
n: 1,
size: '1024x1024',
quality: 'high',
response_format: 'url'
});
return response.data[0].url;
}
// 2. Base64 格式生成并保存
asyncfunctiongenerateAndSave(prompt, filename = 'output.png') {
const response = await openai.images.generate({
model: 'gpt-image-2',
prompt: prompt,
n: 1,
size: '1024x1024',
response_format: 'b64_json'
});
const buffer = Buffer.from(response.data[0].b64_json, 'base64');
fs.writeFileSync(filename, buffer);
console.log(`Image saved to ${filename}`);
}
// 3. 图像编辑
asyncfunctioneditImage(imagePath, maskPath, prompt) {
const response = await openai.images.edit({
image: fs.createReadStream(imagePath),
mask: fs.createReadStream(maskPath),
prompt: prompt,
model: 'gpt-image-1.5',
n: 1,
size: '1024x1024'
});
return response.data[0].url;
}
// 4. 图像变体
asyncfunctioncreateVariations(imagePath, count = 3) {
const response = await openai.images.createVariation({
image: fs.createReadStream(imagePath),
model: 'dall-e-2',
n: count,
size: '1024x1024'
});
return response.data.map(img => img.url);
}
// 5. 视觉理解
asyncfunctionanalyzeImage(imageUrl, question) {
const response = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [
{
role: 'user',
content: [
{ type: 'text', text: question },
{ type: 'image_url', image_url: { url: imageUrl, detail: 'high' } }
]
}
],
max_tokens: 500
});
return response.choices[0].message.content;
}
// 6. 错误处理和重试
asyncfunctiongenerateWithRetry(prompt, maxRetries = 3) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
const response = await openai.images.generate({
model: 'gpt-image-2',
prompt: prompt,
n: 1,
size: '1024x1024'
});
return response.data[0].url;
} catch (error) {
if (error.status === 429 && attempt < maxRetries - 1) {
const waitTime = Math.pow(2, attempt) * 1000; // 指数退避
console.log(`Rate limit hit, waiting ${waitTime}ms...`);
awaitnewPromise(resolve =>setTimeout(resolve, waitTime));
} else {
throw error;
}
}
}
}
// 使用示例
(async () => {
try {
const url = awaitgenerateImage('A futuristic city at sunset');
console.log('Generated image:', url);
awaitgenerateAndSave('A serene mountain landscape', 'mountain.png');
} catch (error) {
console.error('Error:', error.message);
}
})();cURL 完整示例
#!/bin/bash
API_KEY="your-api-key-here"
BASE_URL="https://api.openai.com/v1"
# 1. 基础图像生成
curl $BASE_URL/images/generations \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-image-2",
"prompt": "A futuristic city at sunset, cyberpunk style",
"n": 1,
"size": "1024x1024",
"quality": "high",
"response_format": "url"
}'
# 2. 图像编辑
curl $BASE_URL/images/edits \
-H "Authorization: Bearer $API_KEY" \
-F "image=@original.png" \
-F "mask=@mask.png" \
-F "prompt=A cozy living room with a fireplace" \
-F "model=gpt-image-1.5" \
-F "n=1" \
-F "size=1024x1024"
# 3. 图像变体
curl $BASE_URL/images/variations \
-H "Authorization: Bearer $API_KEY" \
-F "image=@original.png" \
-F "model=dall-e-2" \
-F "n=3" \
-F "size=1024x1024"
# 4. 视觉理解
curl $BASE_URL/chat/completions \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-4o",
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "What is in this image?"
},
{
"type": "image_url",
"image_url": {
"url": "https://example.com/image.jpg",
"detail": "high"
}
}
]
}
],
"max_tokens": 500
}'附录:常见问题解答(FAQ)
Q1: DALL-E 3 已经退役,我应该使用哪个模型?
A: 建议迁移到 GPT Image 2。它提供更好的性能、更高的分辨率(2K)、更快的生成速度(2倍),并支持多语言文本渲染。如果成本是主要考虑因素,可以使用 GPT Image 1 Mini。
Q2: 为什么我的提示词被自动修改了?
A: DALL-E 3 和 GPT Image 系列会自动优化提示词以提升安全性和图像质量。修改后的提示词会在响应的 revised_prompt 字段中返回。这是为了确保生成的图像符合内容政策,并添加更多细节以提升质量。
Q3: 如何生成包含特定文字的图像?
A: 使用 GPT Image 2,它在文本渲染方面表现最佳,支持多语言文字准确渲染。在提示词中明确指定要显示的文字内容,例如:"A poster with the text 'Welcome to 2026' in bold letters"。
Q4: 图像 URL 的有效期是多久?
A: 生成的图像 URL 有效期为 1 小时。如果需要长期保存,建议立即下载图像或使用 response_format: "b64_json" 直接获取图像数据。
Q5: 如何处理速率限制错误(429)?
A: 实现指数退避重试机制:第一次等待 1 秒,第二次等待 2 秒,第三次等待 4 秒,以此类推。同时考虑升级到更高的使用层级以获得更高的速率限制。
Q6: GPT Image 2 支持 Image API 的编辑端点吗?
A:不支持。 gpt-image-2 不支持 Image API 的 /v1/images/edits 端点。
官方支持的模型: dall-e-2, gpt-image-1, gpt-image-1-mini, gpt-image-1.5, chatgpt-image-latest
如需使用 gpt-image-2 进行图像编辑: 请使用 Responses API(Chat Completions API)的 image_generation 工具,该方式支持多图参考编辑、蒙版编辑和高保真输入。
DALL-E 3 也不支持编辑端点。
Q7: 如何降低图像生成成本?
A:
• 使用 GPT Image 1 Mini,成本降低 80% • 选择较低的质量等级(low 而非 high) • 使用较小的尺寸(1024x1024 而非 1792x1024) • 批量生成时使用 n参数而非多次单独请求
Q8: 图像生成失败,返回 400 错误,如何排查?
A: 检查以下几点:
1. 提示词是否违反内容政策(暴力、色情、名人肖像等) 2. 参数值是否有效(模型名称、尺寸、质量等级) 3. 上传的图像是否符合格式要求(PNG、方形、< 4MB) 4. API Key 是否正确且有效
Q9: 可以生成动画或视频吗?
A: 目前 OpenAI 的图像 API 仅支持静态图像生成,不支持动画或视频。如需动画效果,可以生成多帧图像后使用第三方工具合成。
Q10: 如何在生产环境中使用图像 API?
A: 建议:
• 实现完善的错误处理和重试机制 • 使用队列系统处理批量生成任务 • 设置合理的超时时间(30-60秒) • 监控 API 使用量和成本 • 缓存生成的图像以避免重复生成 • 使用 CDN 分发图像以提升访问速度
洞察与总结
API 设计模式分析
RESTful 风格:OpenAI 图像 API 遵循标准的 RESTful 设计,使用清晰的资源路径(/images/generations、/images/edits、/images/variations)和 HTTP 方法(POST)。
统一响应结构:所有端点返回一致的 JSON 结构,包含 created 时间戳和 data 数组,便于客户端统一处理。
多格式支持:同时支持 URL 和 Base64 两种响应格式,兼顾便利性(URL)和灵活性(Base64)。
渐进式增强:从 DALL-E 2 到 GPT Image 2,API 保持向后兼容,同时逐步引入新功能(流式传输、推理能力、更高分辨率)。
能力边界
支持的场景:
• 文本到图像的创意生成 • 基于蒙版的局部图像编辑 • 图像风格变体生成 • 图像内容理解和分析 • 多轮对话中的动态图像生成
不支持的场景:
• 视频或动画生成 • 3D 模型生成 • 实时图像处理(所有操作都是异步的) • 图像超分辨率(upscaling) • 图像到图像的风格迁移(除了变体功能)
技术演进趋势
1. 从专用模型到通用多模态模型:从 DALL-E 系列的专用图像生成模型,演进到基于 GPT-4o 架构的多模态模型(GPT Image 系列) 2. 分辨率持续提升:从 1024x1024 到 2048x2048,未来可能支持更高分辨率 3. 文本渲染能力突破:GPT Image 2 实现了多语言文字的准确渲染,这是图像生成领域的重大突破 4. 推理能力集成:GPT Image 2 内置推理能力,可以在生成前进行网络搜索和自我验证 5. 成本优化路线:推出 Mini 版本,满足不同场景的成本需求
与竞品对比
OpenAI 的优势:
• 完善的 API 和 SDK 支持 • 优秀的文本渲染能力 • 严格的内容审核,适合企业应用 • 与 GPT 系列模型的深度集成
OpenAI 的劣势:
• 价格相对较高 • 分辨率不如部分竞品 • 不支持自托管
选型决策树
需要图像生成功能?
├─ 需要 API 集成?
│ ├─ 是 → 需要文本渲染?
│ │ ├─ 是 → OpenAI GPT Image 2
│ │ └─ 否 → 成本敏感?
│ │ ├─ 是 → OpenAI GPT Image 1 Mini
│ │ └─ 否 → OpenAI GPT Image 1.5
│ └─ 否 → 需要最高质量?
│ ├─ 是 → Midjourney
│ └─ 否 → Stable Diffusion(自托管)
└─ 需要图像理解?
└─ 是 → OpenAI GPT-4o(视觉能力)未来展望
可能的发展方向:
1. 更高分辨率:4K、8K 分辨率支持 2. 视频生成:从静态图像扩展到动态视频 3. 3D 生成:支持 3D 模型和场景生成 4. 实时生成:降低延迟,实现近实时生成 5. 更精细的控制:支持更多参数控制生成过程(如种子、步数、引导强度) 6. 风格一致性:支持跨多张图像保持风格一致 7. 图像到图像:更强大的图像编辑和风格迁移能力
最佳实践总结
提示词工程:
• 使用详细、具体的描述 • 明确指定风格、情绪、色彩 • 避免模糊和抽象的词汇 • 参考 revised_prompt学习优化技巧
成本优化:
• 根据场景选择合适的模型和质量等级 • 使用批量生成而非多次单独请求 • 缓存生成结果避免重复生成 • 监控使用量,设置预算告警
性能优化:
• 实现异步处理和队列系统 • 使用流式传输提供实时反馈 • 设置合理的超时和重试策略 • 使用 CDN 加速图像分发
安全合规:
• 使用 user参数追踪终端用户• 实现内容审核机制 • 遵守 OpenAI 使用政策 • 保护 API Key 安全
参考资源
官方文档
• OpenAI API 参考[1] • 图像生成指南[2] • 视觉能力指南[3] • 工具调用指南[4] • 错误码说明[5] • 定价页面[6]
社区资源
• OpenAI 社区论坛[7] • OpenAI Cookbook[8] • GitHub - OpenAI Python SDK[9] • GitHub - OpenAI Node.js SDK[10]
相关文章
• Mastering OpenAI's New Image Generation API: A Developer's Guide[11] • ChatGPT Images 2.0: A Guide to OpenAI's Next-Gen Image Model[12] • Complete Guide to OpenAI's Latest Image Model (2026)[13] • OpenAI Image Generation API Pricing in 2026[14]
文档生成说明:
本文档由 AI 辅助并基于 WebSearch 搜索结果整理生成,所有信息均附有来源链接。OpenAI 官方文档,部分细节可能需要再次确认。
数据来源: 共搜索 12 个关键词组合,分析了超过 100 个搜索结果,提取了 6 个主要端点的完整信息。
完成时间: 2026-05-07
建议: 在生产环境使用前,请访问 OpenAI 官方文档[15] 确认最新信息。
关键证据来源:
• OpenAI 官方模型页面[16] • OpenAI 官方定价页面[17] • OpenAI 官方 API Reference - Generate[18] • OpenAI 官方 API Reference - Edit[19] • OpenAI 官方 API Reference - Variation[20] • OpenAI 官方 Image Generation Guide[21]
建议
由于本文档依赖二手信息(WebSearch 搜索结果),建议:
1. 在生产环境使用前,直接访问 OpenAI 官方文档[22] 确认 2. 关注 OpenAI 官方更新,API 规格可能随时变化 3. 对于关键功能(如编辑能力、价格),以官方文档为准
Sources:
• OpenAI API Pricing[23] • Create image variation[24] • Mastering OpenAI's New Image Generation API: A Developer's Guide[25] • Error codes[26] • The new ChatGPT Images is here[27] • GPT Image 2 vs GPT Image 1[28] • OpenAI Image Generation API Pricing in 2026[29] • DALL-E 3: vivid vs natural styles compared[30] • gpt-image-1-mini Model[31] • OpenAI API Rate Limits (2026 Update)[32] • Moderation[33] • Azure OpenAI prompt transformation concepts[34] • ChatGPT Images 2.0: A Guide to OpenAI's Next-Gen Image Model[35] • Complete Guide to OpenAI's Latest Image Model (2026)[36]
引用链接
[1] OpenAI API 参考:https://platform.openai.com/docs/api-reference/images[2]图像生成指南:https://platform.openai.com/docs/guides/image-generation[3]视觉能力指南:https://developers.openai.com/api/docs/guides/images-vision[4]工具调用指南:https://developers.openai.com/api/docs/guides/tools-image-generation[5]错误码说明:https://developers.openai.com/api/docs/guides/error-codes[6]定价页面:https://openai.com/api/pricing/[7]OpenAI 社区论坛:https://community.openai.com/[8]OpenAI Cookbook:https://cookbook.openai.com/[9]GitHub - OpenAI Python SDK:https://github.com/openai/openai-python[10]GitHub - OpenAI Node.js SDK:https://github.com/openai/openai-node[11]Mastering OpenAI's New Image Generation API: A Developer's Guide:https://www.cohorte.co/blog/mastering-openais-new-image-generation-api-a-developers-guide[12]ChatGPT Images 2.0: A Guide to OpenAI's Next-Gen Image Model:https://www.datacamp.com/blog/chatgpt-images-2-0[13]Complete Guide to OpenAI's Latest Image Model (2026):https://createvision.ai/guides/gpt-image-2-complete-guide[14]OpenAI Image Generation API Pricing in 2026:https://www.aifreeapi.com/en/posts/openai-image-generation-api-pricing[15]OpenAI 官方文档:https://platform.openai.com/docs/api-reference/images[16]OpenAI 官方模型页面:https://developers.openai.com/api/docs/models/gpt-image-2[17]OpenAI 官方定价页面:https://openai.com/api/pricing/[18]OpenAI 官方 API Reference - Generate:https://developers.openai.com/api/reference/resources/images/methods/generate[19]OpenAI 官方 API Reference - Edit:https://developers.openai.com/api/reference/resources/images/methods/edit[20]OpenAI 官方 API Reference - Variation:https://developers.openai.com/api/reference/resources/images/methods/create_variation[21]OpenAI 官方 Image Generation Guide:https://developers.openai.com/api/docs/guides/image-generation[22]OpenAI 官方文档:https://developers.openai.com/api/docs/models/gpt-image-2[23]OpenAI API Pricing:https://openai.com/api/pricing/[24]Create image variation:https://platform.openai.com/docs/api-reference/images/createVariation[25]Mastering OpenAI's New Image Generation API: A Developer's Guide:https://www.cohorte.co/blog/mastering-openais-new-image-generation-api-a-developers-guide[26]Error codes:https://developers.openai.com/api/docs/guides/error-codes[27]The new ChatGPT Images is here:https://openai.com/index/new-chatgpt-images-is-here/[28]GPT Image 2 vs GPT Image 1:https://framia.pro/page/en-US/news/gpt-image-2-vs-gpt-image-1[29]OpenAI Image Generation API Pricing in 2026:https://www.aifreeapi.com/en/posts/openai-image-generation-api-pricing[30]DALL-E 3: vivid vs natural styles compared:https://taurit.pl/dalle-3-style-vivid-vs-natural/[31]gpt-image-1-mini Model:https://developers.openai.com/api/docs/models/gpt-image-1-mini[32]OpenAI API Rate Limits (2026 Update):https://www.scriptbyai.com/rate-limits-openai-api/[33]Moderation:https://platform.openai.com/docs/guides/moderation[34]Azure OpenAI prompt transformation concepts:https://learn.microsoft.com/en-us/azure/ai-services/openai/concepts/prompt-transformation[35]ChatGPT Images 2.0: A Guide to OpenAI's Next-Gen Image Model:https://www.datacamp.com/blog/chatgpt-images-2-0[36]Complete Guide to OpenAI's Latest Image Model (2026):https://createvision.ai/guides/gpt-image-2-complete-guide
夜雨聆风