OpenAI 圖像生成 API 完全指南:從基礎到實戰(zhàn)

OpenAI 圖像生成 API 完全指南:從基礎到實戰(zhàn)

在當今的AI應用中,圖像生成技術正變得越來越重要。OpenAI提供了強大的圖像生成API,讓開發(fā)者能夠輕松實現從文本提示生成圖像、編輯現有圖像等功能。本文將詳細介紹如何使用OpenAI的圖像生成API,包括基礎概念、實戰(zhàn)示例以及自定義配置等內容。為了方便開發(fā)者接入,推薦通過API中轉站獲取更穩(wěn)定的服務訪問。

概述

OpenAI API允許開發(fā)者通過文本提示生成和編輯圖像,主要使用GPT Image或DALL·E模型。開發(fā)者可以通過兩個API來訪問圖像生成功能:

圖像API(Image API)

圖像API提供三個具有不同功能的端點:

  • 生成(Generations):根據文本提示從頭生成圖像
  • 編輯(Edits):使用新提示修改現有圖像(部分或全部修改)
  • 變體(Variations):生成現有圖像的變體(僅DALL·E 2支持)

該API支持gpt-image-1dall-e-2dall-e-3模型。

響應API(Responses API)

響應API允許在對話或多步驟流程中生成圖像。它支持將圖像生成作為內置工具,并在上下文中接受圖像輸入和輸出。

與圖像API相比,它增加了:

  • 多輪編輯:通過提示對圖像進行高保真度的迭代編輯
  • 靈活輸入:接受圖像文件ID作為輸入圖像,而不僅僅是字節(jié)數據

響應中的圖像生成工具僅支持gpt-image-1。關于支持調用此工具的主模型列表,請參考下面的支持模型部分。

如何選擇合適的API

  • 如果只需要從一個提示生成或編輯單個圖像,圖像API是最佳選擇。
  • 如果想要構建具有GPT Image的對話式、可編輯圖像體驗,或在生成過程中顯示部分圖像,請選擇響應API。

兩種API都允許自定義輸出——調整質量、尺寸、格式、壓縮率,并支持透明背景。

模型對比

我們最新、最先進的圖像生成模型是gpt-image-1,這是一個原生多模態(tài)語言模型。

我們推薦使用該模型,因為它具有高質量的圖像生成能力和在圖像創(chuàng)作中使用世界知識的能力。不過,您也可以通過圖像API使用專門的圖像生成模型——DALL·E 2和DALL·E 3。

模型 端點 用例
DALL·E 2 圖像API:生成、編輯、變體 成本較低,支持并發(fā)請求,支持圖像修復(使用掩碼編輯圖像)
DALL·E 3 圖像API:僅生成 圖像質量高于DALL·E 2,支持更大分辨率
GPT Image 圖像API:生成、編輯 - 響應API支持即將推出 指令遵循能力更強,文本渲染更好,編輯更精細,具備真實世界知識

本指南重點介紹GPT Image,但您也可以切換到DALL·E 2DALL·E 3的文檔。

為確保該模型的負責任使用,在使用gpt-image-1之前,您可能需要從開發(fā)者控制臺完成API組織驗證。

[圖片上傳失敗...(image-a77879-1754112537789)]

生成圖像

您可以使用圖像生成端點基于文本提示創(chuàng)建圖像,或使用響應API中的圖像生成工具在對話中生成圖像。

要了解更多關于自定義輸出(尺寸、質量、格式、透明度)的信息,請參考下面的自定義圖像輸出部分。

您可以設置n參數在單個請求中一次生成多個圖像(默認情況下,API返回單個圖像)。

響應API示例

import OpenAI from "openai";
const openai = new OpenAI({
  baseURL: "https://api.aaaaapi.com" // 使用指定的API基礎地址
});

const response = await openai.responses.create({
    model: "gpt-4.1-mini",
    input: "生成一只灰色虎斑貓抱著戴橙色圍巾的水獺的圖像",
    tools: [{type: "image_generation"}],
});

// 將圖像保存到文件
const imageData = response.output
  .filter((output) => output.type === "image_generation_call")
  .map((output) => output.result);

if (imageData.length > 0) {
  const imageBase64 = imageData[0];
  const fs = await import("fs");
  fs.writeFileSync("otter.png", Buffer.from(imageBase64, "base64"));
}
from openai import OpenAI
import base64

client = OpenAI(
  base_url="https://api.aaaaapi.com"  # 使用指定的API基礎地址
) 

response = client.responses.create(
    model="gpt-4.1-mini",
    input="生成一只灰色虎斑貓抱著戴橙色圍巾的水獺的圖像",
    tools=[{"type": "image_generation"}],
)

// 將圖像保存到文件
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))

圖像API示例

import OpenAI from "openai";
import fs from "fs";
const openai = new OpenAI({
  baseURL: "https://api.aaaaapi.com" // 使用指定的API基礎地址
});

const prompt = `
一本兒童繪本中的插畫:一位獸醫(yī)正在用聽診器聽水獺寶寶的心跳。
`;

const result = await openai.images.generate({
    model: "gpt-image-1",
    prompt,
});

// 將圖像保存到文件
const image_base64 = result.data[0].b64_json;
const image_bytes = Buffer.from(image_base64, "base64");
fs.writeFileSync("otter.png", image_bytes);
from openai import OpenAI
import base64
client = OpenAI(
  base_url="https://api.aaaaapi.com"  # 使用指定的API基礎地址
)

prompt = """
一本兒童繪本中的插畫:一位獸醫(yī)正在用聽診器聽水獺寶寶的心跳。
"""

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

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

// 將圖像保存到文件
with open("otter.png", "wb") as f:
    f.write(image_bytes)
curl -X POST "https://api.aaaaapi.com/v1/images/generations" \
    -H "Authorization: Bearer $OPENAI_API_KEY" \
    -H "Content-type: application/json" \
    -d '{
        "model": "gpt-image-1",
        "prompt": "一本兒童繪本中的插畫:一位獸醫(yī)正在用聽診器聽水獺寶寶的心跳。"
    }' | jq -r '.data[0].b64_json' | base64 --decode > otter.png

多輪圖像生成

使用響應API,您可以構建涉及圖像生成的多輪對話,方法是在上下文中提供圖像生成調用輸出(也可以只使用圖像ID),或使用previous_response_id參數。這使得跨多個輪次迭代圖像變得容易——優(yōu)化提示、應用新指令,并隨著對話的進展改進視覺輸出。

使用previous_response_id

import OpenAI from "openai";
const openai = new OpenAI({
  baseURL: "https://api.aaaaapi.com" // 使用指定的API基礎地址
});

const response = await openai.responses.create({
  model: "gpt-4.1-mini",
  input: "生成一只灰色虎斑貓抱著戴橙色圍巾的水獺的圖像",
  tools: [{ type: "image_generation" }],
});

const imageData = response.output
  .filter((output) => output.type === "image_generation_call")
  .map((output) => output.result);

if (imageData.length > 0) {
  const imageBase64 = imageData[0];
  const fs = await import("fs");
  fs.writeFileSync("cat_and_otter.png", Buffer.from(imageBase64, "base64"));
}

// 后續(xù)跟進
const response_fwup = await openai.responses.create({
  model: "gpt-4.1-mini",
  previous_response_id: response.id,
  input: "現在讓它看起來更真實",
  tools: [{ type: "image_generation" }],
});

const imageData_fwup = response_fwup.output
  .filter((output) => output.type === "image_generation_call")
  .map((output) => output.result);

if (imageData_fwup.length > 0) {
  const imageBase64 = imageData_fwup[0];
  const fs = await import("fs");
  fs.writeFileSync(
    "cat_and_otter_realistic.png",
    Buffer.from(imageBase64, "base64")
  );
}
from openai import OpenAI
import base64

client = OpenAI(
  base_url="https://api.aaaaapi.com"  # 使用指定的API基礎地址
)

response = client.responses.create(
    model="gpt-4.1-mini",
    input="生成一只灰色虎斑貓抱著戴橙色圍巾的水獺的圖像",
    tools=[{"type": "image_generation"}],
)

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))

# 后續(xù)跟進
response_fwup = client.responses.create(
    model="gpt-4.1-mini",
    previous_response_id=response.id,
    input="現在讓它看起來更真實",
    tools=[{"type": "image_generation"}],
)

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))

使用圖像ID

import OpenAI from "openai";
const openai = new OpenAI({
  baseURL: "https://api.aaaaapi.com" // 使用指定的API基礎地址
});

const response = await openai.responses.create({
  model: "gpt-4.1-mini",
  input: "生成一只灰色虎斑貓抱著戴橙色圍巾的水獺的圖像",
  tools: [{ type: "image_generation" }],
});

const imageGenerationCalls = response.output.filter(
  (output) => output.type === "image_generation_call"
);

const imageData = imageGenerationCalls.map((output) => output.result);

if (imageData.length > 0) {
  const imageBase64 = imageData[0];
  const fs = await import("fs");
  fs.writeFileSync("cat_and_otter.png", Buffer.from(imageBase64, "base64"));
}

// 后續(xù)跟進
const response_fwup = await openai.responses.create({
  model: "gpt-4.1-mini",
  input: [
    {
      role: "user",
      content: [{ type: "input_text", text: "現在讓它看起來更真實" }],
    },
    {
      type: "image_generation_call",
      id: imageGenerationCalls[0].id,
    },
  ],
  tools: [{ type: "image_generation" }],
});

const imageData_fwup = response_fwup.output
  .filter((output) => output.type === "image_generation_call")
  .map((output) => output.result);

if (imageData_fwup.length > 0) {
  const imageBase64 = imageData_fwup[0];
  const fs = await import("fs");
  fs.writeFileSync(
    "cat_and_otter_realistic.png",
    Buffer.from(imageBase64, "base64")
  );
}
import openai
import base64

response = openai.responses.create(
    model="gpt-4.1-mini",
    input="生成一只灰色虎斑貓抱著戴橙色圍巾的水獺的圖像",
    tools=[{"type": "image_generation"}],
)

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("cat_and_otter.png", "wb") as f:
        f.write(base64.b64decode(image_base64))

# 后續(xù)跟進
response_fwup = openai.responses.create(
    model="gpt-4.1-mini",
    input=[
        {
            "role": "user",
            "content": [{"type": "input_text", "text": "現在讓它看起來更真實"}],
        },
        {
            "type": "image_generation_call",
            "id": image_generation_calls[0].id,
        },
    ],
    tools=[{"type": "image_generation"}],
)

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))

效果對比

提示 效果
"生成一只灰色虎斑貓抱著戴橙色圍巾的水獺的圖像" 初始圖像
"現在讓它看起來更真實" 優(yōu)化后圖像

流式生成

響應API和圖像API都支持流式圖像生成。這允許您在生成過程中流式傳輸部分圖像,提供更具交互性的體驗。

您可以調整partial_images參數以接收0-3個部分圖像。

  • 如果將partial_images設置為0,您將只接收最終圖像。
  • 對于大于零的值,如果完整圖像生成速度更快,您可能不會收到請求的全部部分圖像數量。

響應API流式示例

import OpenAI from "openai";
import fs from "fs";
const openai = new OpenAI({
  baseURL: "https://api.aaaaapi.com" // 使用指定的API基礎地址
});

const stream = await openai.responses.create({
  model: "gpt-4.1",
  input: "繪制一幅由白色貓頭鷹羽毛組成的河流,蜿蜒穿過寧靜的冬季景觀",
  stream: true,
  tools: [{ type: "image_generation", partial_images: 2 }],
});

for await (const event of stream) {
  if (event.type === "response.image_generation_call.partial_image") {
    const idx = event.partial_image_index;
    const imageBase64 = event.partial_image_b64;
    const imageBuffer = Buffer.from(imageBase64, "base64");
    fs.writeFileSync(`river${idx}.png`, imageBuffer);
  }
}
from openai import OpenAI
import base64

client = OpenAI(
  base_url="https://api.aaaaapi.com"  # 使用指定的API基礎地址
)

stream = client.responses.create(
    model="gpt-4.1",
    input="繪制一幅由白色貓頭鷹羽毛組成的河流,蜿蜒穿過寧靜的冬季景觀",
    stream=True,
    tools=[{"type": "image_generation", "partial_images": 2}],
)

for event in stream:
    if event.type == "response.image_generation_call.partial_image":
        idx = event.partial_image_index
        image_base64 = event.partial_image_b64
        image_bytes = base64.b64decode(image_base64)
        with open(f"river{idx}.png", "wb") as f:
            f.write(image_bytes)

圖像API流式示例

import fs from "fs";
import OpenAI from "openai";

const openai = new OpenAI({
  baseURL: "https://api.aaaaapi.com" // 使用指定的API基礎地址
});

const prompt = "繪制一幅由白色貓頭鷹羽毛組成的河流,蜿蜒穿過寧靜的冬季景觀";
const stream = await openai.images.generate({
  prompt: prompt,
  model: "gpt-image-1",
  stream: true,
  partial_images: 2,
});

for await (const event of stream) {
  if (event.type === "image_generation.partial_image") {
    const idx = event.partial_image_index;
    const imageBase64 = event.b64_json;
    const imageBuffer = Buffer.from(imageBase64, "base64");
    fs.writeFileSync(`river${idx}.png`, imageBuffer);
  }
}
from openai import OpenAI
import base64

client = OpenAI(
  base_url="https://api.aaaaapi.com"  # 使用指定的API基礎地址
)

stream = client.images.generate(
    prompt="繪制一幅由白色貓頭鷹羽毛組成的河流,蜿蜒穿過寧靜的冬季景觀",
    model="gpt-image-1",
    stream=True,
    partial_images=2,
)

for event in stream:
    if event.type == "image_generation.partial_image":
        idx = event.partial_image_index
        image_base64 = event.b64_json
        image_bytes = base64.b64decode(image_base64)
        with open(f"river{idx}.png", "wb") as f:
            f.write(image_bytes)

流式效果對比

部分圖像1 部分圖像2 最終圖像
初始繪制階段 中間繪制階段 完成繪制

優(yōu)化提示詞

在響應API中使用圖像生成工具時,主線模型(如gpt-4.1)會自動優(yōu)化您的提示詞以提高性能。

您可以在圖像生成調用的revised_prompt字段中訪問優(yōu)化后的提示詞:

{
  "id": "ig_123",
  "type": "image_generation_call",
  "status": "completed",
  "revised_prompt": "一只灰色虎斑貓抱著一只水獺。水獺戴著橙色圍巾。兩只動物都很可愛友好,以溫暖、溫馨的風格描繪。",
  "result": "..."
}

編輯圖像

圖像編輯端點允許您:

  • 編輯現有圖像
  • 使用其他圖像作為參考生成新圖像
  • 通過上傳圖像和指示應替換區(qū)域的掩碼來編輯圖像的部分內容(稱為圖像修復

使用圖像參考創(chuàng)建新圖像

您可以使用一個或多個圖像作為參考來生成新圖像。

在這個例子中,我們將使用4個輸入圖像生成一個包含參考圖像中物品的禮品籃新圖像。

[圖片上傳失敗...(image-1ed000-1754112537789)][圖片上傳失敗...(image-ac59c2-1754112537789)][圖片上傳失敗...(image-f6ba52-1754112537789)][圖片上傳失敗...(image-c56ab9-1754112537789)]

[圖片上傳失敗...(image-b04533-1754112537789)]

響應API

使用響應API,您可以通過兩種不同方式提供輸入圖像:

  • 提供Base64編碼的數據URL形式的圖像
  • 提供文件ID(通過文件API創(chuàng)建)

我們正在積極開發(fā)支持將圖像文件的完整URL作為輸入的功能。

創(chuàng)建文件工具函數
from openai import OpenAI
client = OpenAI(
  base_url="https://api.aaaaapi.com"  # 使用指定的API基礎地址
)

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
import fs from "fs";
import OpenAI from "openai";

const openai = new OpenAI({
  baseURL: "https://api.aaaaapi.com" // 使用指定的API基礎地址
});

async function createFile(filePath) {
  const fileContent = fs.createReadStream(filePath);
  const result = await openai.files.create({
    file: fileContent,
    purpose: "vision",
  });
  return result.id;
}
圖像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
function encodeImage(filePath) {
  const base64Image = fs.readFileSync(filePath, "base64");
  return base64Image;
}
編輯圖像示例
from openai import OpenAI
import base64

client = OpenAI(
  base_url="https://api.aaaaapi.com"  # 使用指定的API基礎地址
)

prompt = """生成一張白色背景上的禮品籃逼真圖像,標有"放松身心"字樣,帶有絲帶和手寫風格字體,包含參考圖片中的所有物品。"""

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

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

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.content)
import fs from "fs";
import OpenAI from "openai";

const openai = new OpenAI({
  baseURL: "https://api.aaaaapi.com" // 使用指定的API基礎地址
});

const prompt = `生成一張白色背景上的禮品籃逼真圖像,標有"放松身心"字樣,帶有絲帶和手寫風格字體,包含參考圖片中的所有物品。`;

const base64Image1 = encodeImage("body-lotion.png");
const base64Image2 = encodeImage("soap.png");
const fileId1 = await createFile("body-lotion.png");
const fileId2 = await createFile("incense-kit.png");

const response = await openai.responses.create({
  model: "gpt-4.1",
  input: [
    {
      role: "user",
      content: [
        { type: "input_text", text: prompt },
        {
          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: fileId1,
        },
        {
          type: "input_image",
          file_id: fileId2,
        },
      ],
    },
  ],
  tools: [{ type: "image_generation" }],
});

const imageData = response.output
  .filter((output) => output.type === "image_generation_call")
  .map((output) => output.result);

if (imageData.length > 0) {
  const imageBase64 = imageData[0];
  const fs = await import("fs");
  fs.writeFileSync("gift-basket.png", Buffer.from(imageBase64, "base64"));
} else {
  console.log(response.output.content);
}

圖像API

import base64
from openai import OpenAI
client = OpenAI(
  base_url="https://api.aaaaapi.com"  # 使用指定的API基礎地址
)

prompt = """
生成一張白色背景上的禮品籃逼真圖像,標有"放松身心"字樣,帶有絲帶和手寫風格字體,包含參考圖片中的所有物品。
"""

result = client.images.edit(
    model="gpt-image-1",
    image=[
        open("body-lotion.png", "rb"),
        open("bath-bomb.png", "rb"),
        open("incense-kit.png", "rb"),
        open("soap.png", "rb"),
    ],
    prompt=prompt
)

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

// 將圖像保存到文件
with open("gift-basket.png", "wb") as f:
    f.write(image_bytes)
import fs from "fs";
import OpenAI, { toFile } from "openai";

const client = new OpenAI({
  baseURL: "https://api.aaaaapi.com" // 使用指定的API基礎地址
});

const prompt = `
生成一張白色背景上的禮品籃逼真圖像,標有"放松身心"字樣,帶有絲帶和手寫風格字體,包含參考圖片中的所有物品。
`;

const imageFiles = [
    "bath-bomb.png",
    "body-lotion.png",
    "incense-kit.png",
    "soap.png",
];

const images = await Promise.all(
    imageFiles.map(async (file) =>
        await toFile(fs.createReadStream(file), null, {
            type: "image/png",
        })
    ),
);

const response = await client.images.edit({
    model: "gpt-image-1",
    image: images,
    prompt,
});

// 將圖像保存到文件
const image_base64 = response.data[0].b64_json;
const image_bytes = Buffer.from(image_base64, "base64");
fs.writeFileSync("basket.png", image_bytes);
curl -s -D >(grep -i x-request-id >&2) \
  -o >(jq -r '.data[0].b64_json' | base64 --decode > gift-basket.png) \
  -X POST "https://api.aaaaapi.com/v1/images/edits" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -F "model=gpt-image-1" \
  -F "image[]=@body-lotion.png" \
  -F "image[]=@bath-bomb.png" \
  -F "image[]=@incense-kit.png" \
  -F "image[]=@soap.png" \
  -F 'prompt=生成一張白色背景上的禮品籃逼真圖像,標有"放松身心"字樣,帶有絲帶和手寫風格字體,包含參考圖片中的所有物品。'

使用掩碼編輯圖像(圖像修復)

您可以提供掩碼來指示圖像的哪個部分應該被編輯。

當對GPT Image使用掩碼時,會向模型發(fā)送額外的指令,以幫助指導相應的編輯過程。

與DALL·E 2不同,GPT Image的掩碼完全基于提示。這意味著模型使用掩碼作為指導,但可能不會完全精確地遵循其確切形狀。

如果您提供多個輸入圖像,掩碼將應用于第一個圖像。

響應API

from openai import OpenAI
client = OpenAI(
  base_url="https://api.aaaaapi.com"  # 使用指定的API基礎地址
)

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

response = client.responses.create(
    model="gpt-4o",
    input=[
        {
            "role": "user",
            "content": [
                {
                    "type": "input_text",
                    "text": "生成一張相同的陽光室內休息區(qū)帶泳池的圖像,但泳池中應該有一只火烈鳥",
                },
                {
                    "type": "input_image",
                    "file_id": fileId,
                }
            ],
        },
    ],
    tools=[
        {
            "type": "image_generation",
            "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))
import OpenAI from "openai";
const openai = new OpenAI({
  baseURL: "https://api.aaaaapi.com" // 使用指定的API基礎地址
});

const fileId = await createFile("sunlit_lounge.png");
const maskId = await createFile("mask.png");

const response = await openai.responses.create({
  model: "gpt-4o",
  input: [
    {
      role: "user",
      content: [
        {
          type: "input_text",
          text: "生成一張相同的陽光室內休息區(qū)帶泳池的圖像,但泳池中應該有一只火烈鳥",
        },
        {
          type: "input_image",
          file_id: fileId,
        }
      ],
    },
  ],
  tools: [
    {
      type: "image_generation",
      quality: "high",
      input_image_mask: {
        file_id: maskId,
      },
    },
  ],
});

const imageData = response.output
  .filter((output) => output.type === "image_generation_call")
  .map((output) => output.result);

if (imageData.length > 0) {
  const imageBase64 = imageData[0];
  const fs = await import("fs");
  fs.writeFileSync("lounge.png", Buffer.from(imageBase64, "base64"));
}

圖像API

from openai import OpenAI
client = OpenAI(
  base_url="https://api.aaaaapi.com"  # 使用指定的API基礎地址
)

result = client.images.edit(
    model="gpt-image-1",
    image=open("sunlit_lounge.png", "rb"),
    mask=open("mask.png", "rb"),
    prompt="一個陽光明媚的室內休息區(qū),泳池里有一只火烈鳥"
)

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

// 將圖像保存到文件
with open("composition.png", "wb") as f:
    f.write(image_bytes)
import fs from "fs";
import OpenAI, { toFile } from "openai";

const client = new OpenAI({
  baseURL: "https://api.aaaaapi.com" // 使用指定的API基礎地址
});

const rsp = await client.images.edit({
    model: "gpt-image-1",
    image: await toFile(fs.createReadStream("sunlit_lounge.png"), null, {
        type: "image/png",
    }),
    mask: await toFile(fs.createReadStream("mask.png"), null, {
        type: "image/png",
    }),
    prompt: "一個陽光明媚的室內休息區(qū),泳池里有一只火烈鳥",
});

// 將圖像保存到文件
const image_base64 = rsp.data[0].b64_json;
const image_bytes = Buffer.from(image_base64, "base64");
fs.writeFileSync("lounge.png", image_bytes);
curl -s -D >(grep -i x-request-id >&2) \
  -o >(jq -r '.data[0].b64_json' | base64 --decode > lounge.png) \
  -X POST "https://api.aaaaapi.com/v1/images/edits" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -F "model=gpt-image-1" \
  -F "mask=@mask.png" \   
  -F "image[]=@sunlit_lounge.png" \
  -F 'prompt=一個陽光明媚的室內休息區(qū),泳池里有一只火烈鳥'

圖像修復效果對比

原圖 掩碼 輸出
陽光室內休息區(qū)帶泳池 泳池區(qū)域掩碼 泳池中有火烈鳥的休息區(qū)

掩碼要求

要編輯的圖像和掩碼必須具有相同的格式和大小(大小小于50MB)。

掩碼圖像還必須包含alpha通道。如果您使用圖像編輯工具創(chuàng)建掩碼,請確保將掩碼保存為帶有alpha通道的格式。

為黑白掩碼添加alpha通道

您可以通過編程方式修改黑白圖像以添加alpha通道。

from PIL import Image
from io import BytesIO

# 1. 加載黑白掩碼作為灰度圖像
mask = Image.open(img_path_mask).convert("L")

# 2. 將其轉換為RGBA以留出alpha通道空間
mask_rgba = mask.convert("RGBA")

# 3. 然后使用掩碼本身填充該alpha通道
mask_rgba.putalpha(mask)

# 4. 將掩碼轉換為字節(jié)
buf = BytesIO()
mask_rgba.save(buf, format="PNG")
mask_bytes = buf.getvalue()

# 5. 保存結果文件
img_path_mask_alpha = "mask_alpha.png"
with open(img_path_mask_alpha, "wb") as f:
    f.write(mask_bytes)

輸入保真度

gpt-image-1模型支持高輸入保真度,這使您能夠更好地保留輸出中輸入圖像的細節(jié)。這在使用包含人臉或徽標等元素的圖像時特別有用,這些元素需要在生成的圖像中準確保留。

您可以提供多個輸入圖像,所有圖像都將以高保真度保留,但請記住,第一個圖像將保留更豐富的紋理和更精細的細節(jié),因此如果您包含人臉等元素,請考慮將它們放在第一個圖像中。

要啟用高輸入保真度,請將input_fidelity參數設置為high。默認值為low。

響應API示例

import fs from "fs";
import OpenAI from "openai";

const openai = new OpenAI({
  baseURL: "https://api.aaaaapi.com" // 使用指定的API基礎地址
});
const response = await openai.responses.create({
  model: "gpt-4.1",
  input: [
      {
        role: "user",
        content: [
          { type: "input_text", text: "將徽標添加到女士的上衣上,就像印在面料上一樣。" },
          {
            type: "input_image",
            image_url: "https://cdn.openai.com/API/docs/images/woman_futuristic.jpg",
          },
          {
            type: "input_image",
            image_url: "https://cdn.openai.com/API/docs/images/brain_logo.png",
          },
        ],
      },
    ],
  tools: [{ type: "image_generation", input_fidelity: "high" }],
});

// 提取編輯后的圖像
const imageBase64 = response.output.find(
  (o) => o.type === "image_generation_call"
)?.result;

if (imageBase64) {
  const imageBuffer = Buffer.from(imageBase64, "base64");
  fs.writeFileSync("woman_with_logo.png", imageBuffer);
}
from openai import OpenAI
import base64

client = OpenAI(
  base_url="https://api.aaaaapi.com"  # 使用指定的API基礎地址
)

response = client.responses.create(
    model="gpt-4.1",
    input=[
        {
            "role": "user",
            "content": [
                {"type": "input_text", "text": "將徽標添加到女士的上衣上,就像印在面料上一樣。"},
                {
                    "type": "input_image",
                    "image_url": "https://cdn.openai.com/API/docs/images/woman_futuristic.jpg",
                },
                {
                    "type": "input_image",
                    "image_url": "https://cdn.openai.com/API/docs/images/brain_logo.png",
                },
            ],
        }
    ],
    tools=[{"type": "image_generation", "input_fidelity": "high"}],
)

// 提取編輯后的圖像
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("woman_with_logo.png", "wb") as f:
        f.write(base64.b64decode(image_base64))

圖像API示例

import fs from "fs";
import OpenAI from "openai";

const openai = new OpenAI({
  baseURL: "https://api.aaaaapi.com" // 使用指定的API基礎地址
});
const prompt = "將徽標添加到女士的上衣上,就像印在面料上一樣。";
const result = await openai.images.edit({
  model: "gpt-image-1",
  image: [
    fs.createReadStream("woman.jpg"),
    fs.createReadStream("logo.png")
  ],
  prompt,
  input_fidelity: "high"
});

// 將圖像保存到文件
const image_base64 = result.data[0].b64_json;
const image_bytes = Buffer.from(image_base64, "base64");
fs.writeFileSync("woman_with_logo.png", image_bytes);
from openai import OpenAI
import base64

client = OpenAI(
  base_url="https://api.aaaaapi.com"  # 使用指定的API基礎地址
)

result = client.images.edit(
    model="gpt-image-1",
    image=[open("woman.jpg", "rb"), open("logo.png", "rb")],
    prompt="將徽標添加到女士的上衣上,就像印在面料上一樣。",
    input_fidelity="high"
)

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

// 將圖像保存到文件
with open("woman_with_logo.png", "wb") as f:
    f.write(image_bytes)

高保真度效果對比

輸入1 輸入2 輸出
穿未來風格上衣的女士 腦形徽標 上衣印有徽標的女士

提示:將徽標添加到女士的上衣上,就像印在面料上一樣。

請記住,使用高輸入保真度時,每個請求將使用更多的圖像輸入令牌。要了解成本影響,請參考我們的視覺成本部分。

自定義圖像輸出

您可以配置以下輸出選項:

  • 尺寸(Size):圖像尺寸(例如1024x1024、1024x1536
  • 質量(Quality):渲染質量(例如low、medium、high
  • 格式(Format):文件輸出格式
  • 壓縮(Compression):JPEG和WebP格式的壓縮級別(0-100%)
  • 背景(Background):透明或不透明

size、qualitybackground支持auto選項,模型將根據提示自動選擇最佳選項。

尺寸和質量選項

標準質量的正方形圖像生成速度最快。默認尺寸為1024x1024像素。

可用尺寸 1024x1024(正方形)、1536x1024(橫向)、1024x1536(縱向)、auto(默認)
質量選項 low、medium、high、auto(默認)

輸出格式

圖像API返回Base64編碼的圖像數據。默認格式是png,但您也可以請求jpegwebp。

如果使用jpegwebp,您還可以指定output_compression參數來控制壓縮級別(0-100%)。例如,output_compression=50將把圖像壓縮50%。

使用jpegpng更快,因此如果延遲是一個問題,您應該優(yōu)先選擇這種格式。

透明度

gpt-image-1模型支持透明背景。要啟用透明度,請將background參數設置為transparent。

它僅支持pngwebp輸出格式。

透明度在將質量設置為mediumhigh時效果最佳。

響應API示例

import openai
import base64

response = openai.responses.create(
    model="gpt-4.1-mini",
    input="繪制一個2D像素藝術風格的灰色虎斑貓精靈表",
    tools=[
        {
            "type": "image_generation",
            "background": "transparent",
            "quality": "high",
        }
    ],
)

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("sprite.png", "wb") as f:
        f.write(base64.b64decode(image_base64))
import fs from "fs";
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.aaaaapi.com" // 使用指定的API基礎地址
});

const response = await client.responses.create({
  model: "gpt-4.1-mini",
  input: "繪制一個2D像素藝術風格的灰色虎斑貓精靈表",
  tools: [
    {
      type: "image_generation",
      background: "transparent",
      quality: "high",
    },
  ],
});

const imageData = response.output
  .filter((output) => output.type === "image_generation_call")
  .map((output) => output.result);

if (imageData.length > 0) {
  const imageBase64 = imageData[0];
  const imageBuffer = Buffer.from(imageBase64, "base64");
  fs.writeFileSync("sprite.png", imageBuffer);
}

圖像API示例

import OpenAI from "openai";
import fs from "fs";
const openai = new OpenAI({
  baseURL: "https://api.aaaaapi.com" // 使用指定的API基礎地址
});

const result = await openai.images.generate({
    model: "gpt-image-1",
    prompt: "繪制一個2D像素藝術風格的灰色虎斑貓精靈表",
    size: "1024x1024",
    background: "transparent",
    quality: "high",
});

// 將圖像保存到文件
const image_base64 = result.data[0].b64_json;
const image_bytes = Buffer.from(image_base64, "base64");
fs.writeFileSync("sprite.png", image_bytes);
from openai import OpenAI
import base64
client = OpenAI(
  base_url="https://api.aaaaapi.com"  # 使用指定的API基礎地址
)

result = client.images.generate(
    model="gpt-image-1",
    prompt="繪制一個2D像素藝術風格的灰色虎斑貓精靈表",
    size="1024x1024",
    background="transparent",
    quality="high",
)

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

// 將圖像保存到文件
with open("sprite.png", "wb") as f:
    f.write(image_bytes)
curl -X POST "https://api.aaaaapi.com/v1/images" \
    -H "Authorization: Bearer $OPENAI_API_KEY" \
    -H "Content-type: application/json" \
    -d '{
        "prompt": "繪制一個2D像素藝術風格的灰色虎斑貓精靈表",
        "quality": "high",
        "size": "1024x1024",
        "background": "transparent"
    }' | jq -r 'data[0].b64_json' | base64 --decode > sprite.png

局限性

GPT Image 1模型是一個強大且多功能的圖像生成模型,但仍有一些局限性需要注意:

  • 延遲:復雜提示可能需要長達2分鐘的處理時間。
  • 文本渲染:盡管比DALL·E系列有顯著改進,但該模型在精確文本放置和清晰度方面仍可能存在困難。
  • 一致性:雖然能夠生成一致的圖像,但該模型在多次生成中可能偶爾難以保持重復角色或品牌元素的視覺一致性。
  • 構圖控制:盡管指令遵循能力有所提高,但該模型在結構化或布局敏感的構圖中精確定位元素可能有困難。

內容審核

所有提示和生成的圖像都按照我們的內容政策進行過濾。

對于使用gpt-image-1的圖像生成,您可以通過moderation參數控制審核嚴格程度。該參數支持兩個值:

  • auto(默認):標準過濾,旨在限制創(chuàng)建某些可能與年齡不適當的內容類別。
  • low:限制性較低的過濾。

支持模型

在響應API中使用圖像生成時,支持調用此工具的模型有:

  • gpt-4o
  • gpt-4o-mini
  • gpt-4.1
  • gpt-4.1-mini
  • gpt-4.1-nano
  • o3

成本和延遲

該模型通過首先生成專門的圖像令牌來生成圖像。延遲和最終成本都與渲染圖像所需的令牌數量成正比——更大的圖像尺寸和更高的質量設置會產生更多的令牌。

生成的令牌數量取決于圖像尺寸和質量:

質量 正方形(1024×1024) 縱向(1024×1536) 橫向(1536×1024)
272 令牌 408 令牌 400 令牌
1056 令牌 1584 令牌 1568 令牌
4160 令牌 6240 令牌 6208 令牌

請注意,您還需要考慮輸入令牌:提示的文本令牌和編輯圖像時的輸入圖像令牌。如果使用高輸入保真度,輸入令牌的數量將會更高。

有關文本和圖像令牌價格的更多信息,請參考我們的定價頁面。

因此,最終成本是以下各項的總和:

  • 輸入文本令牌
  • 使用編輯端點時的輸入圖像令牌
  • 圖像輸出令牌

部分圖像成本

如果您想使用partial_images參數流式傳輸圖像生成,每個部分圖像將額外產生100個圖像輸出令牌。

通過本文的介紹,相信您已經對OpenAI圖像生成API有了全面的了解。如需開始使用,可通過API中轉站快速接入,享受更穩(wěn)定的服務體驗。無論是構建創(chuàng)意工具、電商應用還是內容生成平臺,圖像生成API都能為您的項目增添強大的視覺生成能力。

?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容