For the complete documentation index, see llms.txt. Markdown versions of documentation pages are available by appending .md to the page URL.
主导航

图像生成

了解如何生成或编辑图像。

概览

通过 API,您可以使用 gpt-image-2.5-sunburstgpt-image-2.5-flare 根据文本提示生成和编辑图像。如果工作流最注重编辑精度,请选择 Sunburst;如果需要快速生成高质量的日常图像,请选择 Flare。您可以通过以下两个 API 使用图像生成功能:

Image API

Image API 提供两个端点,各有不同的功能:

Responses API

Responses API 让您可以在对话或多步骤流程中生成图像。它将图像生成功能作为内置工具提供,并支持在上下文中包含图像输入和输出。

与 Image API 相比,它增加了以下功能:

  • 多轮编辑:通过提示对图像进行多轮高保真编辑
  • 灵活的输入:不仅支持字节数据,还支持使用图像的文件 ID 作为图像输入

有关哪些主系列模型可以调用图像生成工具,请参阅支持的模型

选择合适的 API

  • 如果您只需要根据一条提示生成或编辑一张图像,Image API 是最佳选择。
  • 如果您想使用 GPT Image 构建可通过对话编辑图像的体验,请选择 Responses API。

使用 Image API 时,请直接将 model 设置为 gpt-image-2.5-sunburstgpt-image-2.5-flare。使用 Responses API 时,请在顶层选择受支持的主系列模型,并在图像生成工具的 model 字段中指定 gpt-image-2.5-sunburstgpt-image-2.5-flare

这两个 API 都支持通过调整质量、尺寸、格式和压缩程度来自定义输出

为确保以负责任的方式使用这些模型,在使用 GPT Image 模型之前, 您可能需要在开发者 控制台中 完成API 组织 验证

木桌上的米色咖啡杯

生成图像

您可以使用图像生成端点根据文本提示创建图像,也可以使用 Responses API 中的图像生成工具在对话中生成图像。

如需详细了解如何自定义输出(尺寸、质量、格式、压缩程度),请参阅下文的自定义图像输出部分。

您可以设置 n 参数,在单个请求中一次生成多张图像(默认情况下,API 返回一张图像)。

生成一张图像
from openai import OpenAI
import base64

client = OpenAI()

prompt = """
A children's book drawing of a veterinarian using a stethoscope to
listen to the heartbeat of a baby otter.
"""

result = client.images.generate(model="gpt-image-2.5-sunburst", prompt=prompt)

image_base64 = result.data[0].b64_json
image_bytes = base64.b64decode(image_base64)

# Save the image to a file
with open("otter.png", "wb") as f:
    f.write(image_bytes)

多轮图像生成

使用 Responses API,您可以在上下文中提供图像生成调用的输出(也可以只使用图像 ID),或使用 previous_response_id 参数,构建包含图像生成的多轮对话。 这样,您就能在多轮对话中迭代图像,随着对话的推进优化提示、应用新指令,并不断调整视觉输出。

使用 Responses API 的图像生成工具时,受支持的工具模型可以选择生成新图像,或编辑对话中已有的图像。可选的 action 参数用于控制这一行为:保留 action: "auto" 让模型自行决定;设置 action: "generate" 始终创建新图像;或设置 action: "edit",在上下文中有图像时强制执行编辑。

使用 action 强制创建图像
from openai import OpenAI
import base64

client = OpenAI()

response = client.responses.create(
    model="gpt-6-astra",
    input="Generate an image of gray tabby cat hugging an otter with an orange scarf",
    tools=[
        {"type": "image_generation", "model": "gpt-image-2.5-sunburst", "action": "generate"}
    ],
)

# Save the image to a file
image_data = [
    output.result
    for output in response.output
    if output.type == "image_generation_call"
]

if image_data:
    image_base64 = image_data[0]
    with open("otter.png", "wb") as f:
        f.write(base64.b64decode(image_base64))

如果您未在上下文中提供图像就强制执行 edit,调用将返回错误。将 action 保持为 auto,即可让模型决定何时生成或编辑图像。

多轮图像生成
from openai import OpenAI
import base64

client = OpenAI()

response = client.responses.create(
    model="gpt-6-astra",
    input="Generate an image of gray tabby cat hugging an otter with an orange scarf",
    tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],
)

image_data = [
    output.result
    for output in response.output
    if output.type == "image_generation_call"
]

if image_data:
    image_base64 = image_data[0]

    with open("cat_and_otter.png", "wb") as f:
        f.write(base64.b64decode(image_base64))


# Follow up

response_fwup = client.responses.create(
    model="gpt-6-astra",
    previous_response_id=response.id,
    input="Now make it look realistic",
    tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],
)

image_data_fwup = [
    output.result
    for output in response_fwup.output
    if output.type == "image_generation_call"
]

if image_data_fwup:
    image_base64 = image_data_fwup[0]
    with open("cat_and_otter_realistic.png", "wb") as f:
        f.write(base64.b64decode(image_base64))

结果

“生成一张图像:一只灰色虎斑猫抱着一只戴橙色围巾的水獭”

一只猫和一只水獭

“现在把它改成写实风格”

一只猫和一只水獭

流式传输

Responses API 和 Image API 支持流式图像生成。您可以在 API 生成图像的过程中流式接收中间图像,提供更具交互性的体验。

您可以调整 partial_images 参数,以接收 0-3 张中间图像。

  • 如果将 partial_images 设为 0,您将只收到最终图像。
  • 当该值大于零时,如果完整图像生成得较快,您收到的中间图像数量可能少于请求的数量。
流式传输图像
from openai import OpenAI
import base64

client = OpenAI()


def save_base64_image(filename, image_base64):
    image_bytes = base64.b64decode(image_base64)
    with open(filename, "wb") as f:
        f.write(image_bytes)


stream = client.responses.create(
    model="gpt-6-astra",
    input="Draw a gorgeous image of a river made of white owl feathers, snaking its way through a serene winter landscape",
    stream=True,
    tools=[
        {"type": "image_generation", "model": "gpt-image-2.5-sunburst", "partial_images": 2}
    ],
)

for event in stream:
    if event.type == "response.image_generation_call.partial_image":
        idx = event.partial_image_index
        save_base64_image(f"river-partial-{idx}.png", event.partial_image_b64)
    elif event.type == "response.completed":
        image_data = [
            output.result
            for output in event.response.output
            if output.type == "image_generation_call"
        ]

        if image_data:
            save_base64_image("river-final.png", image_data[0])

结果

中间图像 1中间图像 2最终图像
第 1 张中间图像第 2 张中间图像最终图像

提示:绘制一幅绚丽的画面,一条由白色猫头鹰羽毛组成的河流蜿蜒穿过宁静的冬日景色

修订后的提示

在 Responses API 中使用图像生成工具时,主系列模型(例如 gpt-5.5)会自动修订您的提示,以改善生成效果。

您可以在图像生成调用的 revised_prompt 字段中获取修订后的提示:

包含修订后提示的响应
{
  "id": "ig_123",
  "type": "image_generation_call",
  "status": "completed",
  "revised_prompt": "A gray tabby cat hugging an otter. The otter is wearing an orange scarf. Both animals are cute and friendly, depicted in a warm, heartwarming style.",
  "result": "..."
}

编辑图像

图像编辑端点支持以下操作:

  • 编辑现有图像
  • 以其他图像为参考生成新图像
  • 上传图像和标明待替换区域的蒙版,编辑图像的局部区域

使用参考图像创建新图像

您可以使用一张或多张图像作为参考,生成新图像。

在此示例中,我们将使用 4 张输入图像,生成一张新的礼品篮图像,篮中装有参考图像中的物品。

身体乳香皂熏香套装泡澡球
沐浴礼盒

使用 Responses API 时,您可以通过以下 3 种方式提供输入图像:

  • 提供完整的 URL
  • 以 Base64 编码的数据 URL 形式提供图像
  • 提供文件 ID(通过 Files API 创建)

创建文件

创建文件
from openai import OpenAI

client = OpenAI()


def create_file(file_path):
    with open(file_path, "rb") as file_content:
        result = client.files.create(
            file=file_content,
            purpose="vision",
        )
        return result.id

创建 base64 编码的图像

创建 base64 编码的图像
import base64


def encode_image(file_path):
    with open(file_path, "rb") as f:
        base64_image = base64.b64encode(f.read()).decode("utf-8")
    return base64_image
编辑图像
from openai import OpenAI
import base64

client = OpenAI()


def encode_image(file_path):
    with open(file_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode("utf-8")


def create_file(file_path):
    with open(file_path, "rb") as file_content:
        result = client.files.create(file=file_content, purpose="vision")
    return result.id


prompt = """Generate a photorealistic image of a gift basket on a white background
labeled 'Relax & Unwind' with a ribbon and handwriting-like font,
containing all the items in the reference pictures."""

base64_image1 = encode_image("body-lotion.png")
base64_image2 = encode_image("soap.png")
file_id1 = create_file("bath-bomb.png")
file_id2 = create_file("incense-kit.png")

response = client.responses.create(
    model="gpt-6-astra",
    input=[
        {
            "role": "user",
            "content": [
                {"type": "input_text", "text": prompt},
                {
                    "type": "input_image",
                    "image_url": f"data:image/png;base64,{base64_image1}",
                },
                {
                    "type": "input_image",
                    "image_url": f"data:image/png;base64,{base64_image2}",
                },
                {
                    "type": "input_image",
                    "file_id": file_id1,
                },
                {
                    "type": "input_image",
                    "file_id": file_id2,
                },
            ],
        }
    ],
    tools=[{"type": "image_generation", "model": "gpt-image-2.5-sunburst"}],
)

image_generation_calls = [
    output for output in response.output if output.type == "image_generation_call"
]

image_data = [output.result for output in image_generation_calls]

if image_data:
    image_base64 = image_data[0]
    with open("gift-basket.png", "wb") as f:
        f.write(base64.b64decode(image_base64))
else:
    print(response.output_text)

使用蒙版编辑图像

您可以提供蒙版,指定图像中需要编辑的区域。

在 GPT Image 中使用蒙版时,系统会向模型发送额外指令,引导模型完成相应的编辑。

GPT Image 的蒙版编辑完全基于提示。模型会将蒙版作为参考,但可能无法完全精确地遵循其形状。

如果您提供多张输入图像,蒙版将应用于第一张图像。

使用蒙版编辑图像
from openai import OpenAI
import base64

client = OpenAI()


def create_file(file_path):
    with open(file_path, "rb") as file_content:
        result = client.files.create(file=file_content, purpose="vision")
    return result.id


fileId = create_file("sunlit_lounge.png")
maskId = create_file("mask.png")

response = client.responses.create(
    model="gpt-6-astra",
    input=[
        {
            "role": "user",
            "content": [
                {
                    "type": "input_text",
                    "text": "generate an image of the same sunlit indoor lounge area with a pool but the pool should contain a flamingo",
                },
                {
                    "type": "input_image",
                    "file_id": fileId,
                },
            ],
        },
    ],
    tools=[
        {
            "type": "image_generation",
            "model": "gpt-image-2.5-sunburst",
            "quality": "high",
            "input_image_mask": {
                "file_id": maskId,
            },
        },
    ],
)

image_data = [
    output.result
    for output in response.output
    if output.type == "image_generation_call"
]

if image_data:
    image_base64 = image_data[0]
    with open("lounge.png", "wb") as f:
        f.write(base64.b64decode(image_base64))
图像蒙版输出
带泳池的粉色房间覆盖泳池部分区域的蒙版原来的泳池,蒙版区域已替换为充气火烈鸟

提示:阳光照耀的室内休闲区,泳池中有一只火烈鸟

蒙版要求

待编辑图像和蒙版必须采用相同的格式和尺寸,文件大小均须小于 50MB。

蒙版图像还必须包含 alpha 通道。如果您使用图像编辑工具创建蒙版,请确保保存时保留 alpha 通道。

您可以通过编程修改黑白图像,为其添加 alpha 通道。

为黑白蒙版添加 alpha 通道
from PIL import Image
from io import BytesIO

# 1. Load your black & white mask as a grayscale image
mask = Image.open("mask.png").convert("L")

# 2. Convert it to RGBA so it has space for an alpha channel
mask_rgba = mask.convert("RGBA")

# 3. Then use the mask itself to fill that alpha channel
mask_rgba.putalpha(mask)

# 4. Convert the mask into bytes
buf = BytesIO()
mask_rgba.save(buf, format="PNG")
mask_bytes = buf.getvalue()

# 5. Save the resulting file
img_path_mask_alpha = "mask_alpha.png"
with open(img_path_mask_alpha, "wb") as f:
    f.write(mask_bytes)

自定义图像输出

您可以配置以下输出选项:

  • 尺寸:图像的宽高(例如,1024x10241024x1536
  • 质量:渲染质量(例如,lowmediumhigh
  • 格式:输出文件的格式
  • 压缩:JPEG 和 WebP 格式的压缩级别(0-100%)
  • 背景:透明、不透明或自动

sizequalitybackground 均支持 auto 选项,模型会根据提示自动选择最佳选项。

尺寸和质量选项

gpt-image-2.5-sunburstgpt-image-2.5-flare 新增了 xhighmax 质量设置,两款模型均默认为 auto。较早的 GPT Image 模型最高支持 high 质量设置。

设置选项
推荐尺寸1024x1024(正方形)、1536x1024(横向)、1024x1536(纵向)
质量lowmediumhighxhighmaxauto

两款模型还支持以 WIDTHxHEIGHT 字符串指定自定义尺寸,例如 1536x864。宽度和高度必须是 16 的整数倍,宽高比必须介于 1:3 和 3:1 之间,且任一边长均不得超过 3840 像素。总像素数必须介于 655,360 和 8,294,400(4K)之间。对高于 2560x1440 的分辨率的支持尚处于实验阶段。

使用任一模型生成透明背景时,请设置 background: "transparent",并使用 output_format: "png""webp"

使用 quality: "low" 可快速生成草稿。生成最终素材时,请比较更高的质量设置,在细节、延迟和费用之间找到合适的平衡。

输出格式

Image API 返回 base64 编码的图像数据。 默认格式为 png,您也可以请求 jpegwebp 格式。

如果使用 jpegwebp,您还可以通过 output_compression 参数控制压缩级别(0-100%)。例如,output_compression=50 会将图像压缩 50%。

使用 jpegpng 更快,因此,如果您关注延迟, 应优先选择此格式。

局限性

GPT Image 模型是功能强大、用途广泛的图像生成模型,但仍有一些局限性需要注意:

  • 延迟: 复杂提示的处理时间可能长达 2 分钟。
  • 文本渲染: 虽然已有显著改进,但模型在精确放置文本和确保文本清晰度方面仍可能遇到困难。
  • 一致性: 虽然模型能够生成视觉一致的图像,但在多次生成中,偶尔仍难以保持重复出现的角色或品牌元素的视觉一致性。
  • 构图控制: 虽然遵循指令的能力有所提升,但对于有明确结构或对布局要求较高的构图,模型仍可能难以精确放置元素。

内容审核

所有提示和生成的图像都会依据我们的内容政策进行过滤。

使用 GPT Image 模型生成图像时,您可以通过 moderation 参数控制内容审核的严格程度。此参数支持两个值:

  • auto(默认):标准过滤,旨在限制生成某些类别的、可能不适合特定年龄段的内容。
  • low:限制较少的过滤。

处理被拦截的请求和其他错误

处理图像生成失败的方式与处理其他 API 错误相同:检查 HTTP 状态或 SDK 异常类型,记录请求 ID,并参阅错误代码指南,了解身份验证、配额、速率限制和服务器故障。对于暂时性的速率限制和服务器故障,请采用退避策略重试。对于配额错误或需要修改请求的图像生成用户错误,请勿自动重试。

部分图像生成失败可由用户修正,并可能返回 error.type = "image_generation_user_error"。在未修改提示或输入图像的情况下,请勿自动重试这些错误。通过程序处理时,请使用 error.code 作为稳定的判别依据。

error.code = "moderation_blocked" 时,错误还可能包含一个可选的 error.moderation_details 对象:

{
  "error": {
    "type": "image_generation_user_error",
    "code": "moderation_blocked",
    "moderation_details": {
      "moderation_stage": "input",
      "categories": ["harassment"]
    }
  }
}

moderation_details 对象提供概略的调试上下文,不会暴露内部分类器的标签或分数。

moderation_stage 的可能取值为:

  • input:拦截由提示或请求输入触发。
  • output:拦截由生成的图像或下游输出审核阶段触发。
  • unknown:难以确定拦截来源时使用的备用值,较为少见。

categories 包含粗粒度的公开标签。例如,您可能会看到 harassmentself-harmsexualviolence 等值。

对于大多数应用,面向最终用户的主要提示消息应采用通用表述。将 moderation_details 用于开发者日志、支持工作流、分析和简要的修正建议。

处理被内容审核拦截的图像生成错误
import OpenAI from "openai";

const openai = new OpenAI();

try {
  // The same error handling pattern applies to image generation requests,
  // image edits, and Responses API tool calls that generate images.
  await openai.images.generate({
    model: "gpt-image-2.5-sunburst",
    prompt: "Create a poster humiliating my coworker with insulting captions",
  });
} catch (error) {
  if (error?.code !== "moderation_blocked") {
    throw error;
  }

  const moderationDetails = error.error?.moderation_details;
  const categories = moderationDetails?.categories ?? [];
  const stage = moderationDetails?.moderation_stage;

  let hint =
    "This request could not be completed because it did not meet safety requirements.";

  if (categories.includes("harassment")) {
    hint =
      "Try removing abusive or targeting language and focus on neutral visual details instead.";
  } else if (stage === "input") {
    hint =
      "Try revising the prompt or input images and submit the request again.";
  } else if (stage === "output") {
    hint =
      "The generated result was blocked by a safety check. Try changing the prompt and generating again.";
  }

  console.error("Image generation blocked", {
    request_id: error?.requestID,
    code: error?.code,
    moderation_details: moderationDetails,
  });

  console.log(hint);
}

支持的模型

在 Responses API 中使用图像生成时,gpt-5 及更新的模型应当支持图像生成工具。请查看相应模型的详情页,确认您想使用的模型是否可以使用图像生成工具。

费用与延迟

GPT Image 2.5 费用

Responses API 请求除了产生图像生成费用,还会计入主模型的 Token 用量。

两款 GPT Image 2.5 模型采用相同的 Token 费率:图像输入 Token 每百万 8 美元,缓存图像输入 Token 每百万 2 美元,图像输出 Token 每百万 30 美元,文本输入 Token 每百万 5 美元,缓存文本输入 Token 每百万 1.25 美元。请参阅定价

使用响应中的 usage 衡量您的提示、尺寸和质量设置所消耗的 Token 数量。Token 费率相同并不意味着每张图像的费用相同:Token 消耗量可能因模型和质量设置而异。有关旧版模型的定价示例,请参阅早期 GPT Image 模型

GPT Image 2.5 和 GPT Image 2 输出 Token

选择模型、质量和尺寸,以估算输出 Token 数量和图像输出费用。 对于 gpt-image-2.5-sunburstgpt-image-2.5-flare,质量选项为 lowmediumhighxhighmax。 对于 gpt-image-2,选项为 lowmediumhigh。 在相同质量设置下,各模型可能消耗不同数量的 Token,但每个图像输出 Token 的价格相同。 估算时请指定明确的质量和尺寸值;auto 的结果取决于生成的图像。

模型
质量
输出 Token
196
预计图像输出费用
$0.00588

按每百万图像输出 Token 30 美元计算的单张图像费用。不包含文本和图像输入 Token,以及流式传输的部分图像费用。

部分图像费用

如果您要使用 partial_images 参数流式传输生成的图像,每张部分图像将额外消耗 100 个图像输出 Token。

早期 GPT Image 模型

以下详情适用于早期模型,不适用于 Sunburst 或 Flare。对于新的集成,请使用上述 GPT Image 2.5 模型之一。

GPT Image 2 设置与输入保真度

只要满足以下约束,gpt-image-2size 参数就接受任意分辨率。正方形图像通常生成得最快。

常用尺寸
  • 1024x1024(正方形)

  • 1536x1024(横向)

  • 1024x1536(竖向)

  • 2048x2048(2K 正方形)

  • 2048x1152(2K 横向)

  • 3840x2160(4K 横向)

  • 2160x3840(4K 竖向)

  • auto(默认)

尺寸约束
  • 最大边长必须小于或等于 3840px

  • 两条边的长度都必须是 16px 的整数倍

  • 长边与短边的比例不得超过 3:1

  • 总像素数必须大于或等于 655,360,且小于或等于 8,294,400

质量选项
  • low
  • medium
  • high
  • auto(默认)

图像输入保真度

input_fidelity 参数用于控制模型在图像编辑和参考图像工作流中保留输入图像细节的程度。使用 gpt-image-2 时,请省略此参数;该模型会自动以高保真度处理每张输入图像,因此 API 不允许更改此参数。

由于 gpt-image-2 始终以高保真度处理输入图像, 包含参考图像的编辑请求可能会消耗更多图像输入 Token。 要了解这对费用的影响,请参阅视觉 费用 部分。

旧版模型定价示例

gpt-image-2 之前的模型

gpt-image-2 之前的 GPT Image 模型会先生成专用的图像 Token,再生成图像。延迟和最终费用均与渲染图像所需的 Token 数量成正比:图像尺寸越大、质量设置越高,生成的 Token 就越多。

生成的 Token 数量取决于图像尺寸和质量:

质量正方形(1024×1024)竖向(1024×1536)横向(1536×1024)
272 个 Token408 个 Token400 个 Token
1056 个 Token1584 个 Token1568 个 Token
4160 个 Token6240 个 Token6208 个 Token

请注意,您还需要计入输入 Token:提示的文本 Token,以及编辑图像时输入图像的图像 Token。 由于 gpt-image-2 始终以高保真度处理输入图像,包含参考图像的编辑请求可能会消耗更多输入 Token。

请参阅定价页面,了解当前的 文本和图像 Token 价格,并使用下方的计算费用 部分估算请求费用。

最终费用为以下各项费用之和:

  • 输入文本 Token
  • 输入图像 Token(使用编辑端点时)
  • 图像输出 Token

计算费用

使用下方的定价计算器估算 GPT Image 模型的请求费用。 gpt-image-2 支持数千种有效分辨率;下表列出了 与早期 GPT Image 模型相同的尺寸,方便比较。下方还列出了 GPT Image 1.5、 GPT Image 1 和 GPT Image 1 Mini 的 旧版单张图像输出定价表。估算请求总费用时, 您仍需计入文本和图像输入 Token。

在相同的质量设置下,较大的非正方形分辨率有时会比 较小的分辨率或正方形分辨率产生更少的输出 Token。

模型

质量

1024 x 1024 1024 x 1536 1536 x 1024

GPT Image 2


支持更多尺寸
$0.006 $0.005 $0.005
$0.053 $0.041 $0.041
$0.211 $0.165 $0.165

GPT Image 1.5

$0.009 $0.013 $0.013
$0.034 $0.05 $0.05
$0.133 $0.2 $0.2

GPT Image 1

$0.011 $0.016 $0.016
$0.042 $0.063 $0.063
$0.167 $0.25 $0.25

GPT Image 1 Mini

$0.005 $0.006 $0.006
$0.011 $0.015 $0.015
$0.036 $0.052 $0.052