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,它還提供:

  • 多輪編輯:透過提示詞反覆對圖像進行高傳真度編輯
  • 彈性輸入:除了位元組資料,也接受圖像的 File 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 都能讓你調整品質、尺寸、格式及壓縮程度,以自訂輸出

為確保這些模型以負責任的方式使用,你可能需要先在開發者 控制台 完成 API 組織 驗證, 才能使用 GPT Image 模型。

木桌上的米色咖啡杯

生成圖像

你可以使用圖像生成端點,根據文字提示詞建立圖像,也可以使用 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 的品質選項為 lowmediumhighxhighmaxgpt-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