OpenAI 图像生成 API 完全指南:从基础到实战
在当今的AI应用中,图像生成技术正变得越来越重要。OpenAI提供了强大的图像生成API,让开发者能够轻松实现从文本提示生成图像、编辑现有图像等功能。本文将详细介绍如何使用OpenAI的图像生成API,包括基础概念、实战示例以及自定义配置等内容。为了方便开发者接入,推荐通过API中转站获取更稳定的服务访问。
概述
OpenAI API允许开发者通过文本提示生成和编辑图像,主要使用GPT Image或DALL·E模型。开发者可以通过两个API来访问图像生成功能:
图像API(Image API)
图像API提供三个具有不同功能的端点:
- 生成(Generations):根据文本提示从头生成图像
- 编辑(Edits):使用新提示修改现有图像(部分或全部修改)
- 变体(Variations):生成现有图像的变体(仅DALL·E 2支持)
该API支持gpt-image-1、dall-e-2和dall-e-3模型。
响应API(Responses API)
响应API允许在对话或多步骤流程中生成图像。它支持将图像生成作为内置工具,并在上下文中接受图像输入和输出。
与图像API相比,它增加了:
- 多轮编辑:通过提示对图像进行高保真度的迭代编辑
- 灵活输入:接受图像文件ID作为输入图像,而不仅仅是字节数据
响应中的图像生成工具仅支持gpt-image-1。关于支持调用此工具的主模型列表,请参考下面的支持模型部分。
如何选择合适的API
- 如果只需要从一个提示生成或编辑单个图像,图像API是最佳选择。
- 如果想要构建具有GPT Image的对话式、可编辑图像体验,或在生成过程中显示部分图像,请选择响应API。
两种API都允许自定义输出——调整质量、尺寸、格式、压缩率,并支持透明背景。
模型对比
我们最新、最先进的图像生成模型是gpt-image-1,这是一个原生多模态语言模型。
我们推荐使用该模型,因为它具有高质量的图像生成能力和在图像创作中使用世界知识的能力。不过,您也可以通过图像API使用专门的图像生成模型——DALL·E 2和DALL·E 3。
| 模型 | 端点 | 用例 |
|---|---|---|
| DALL·E 2 | 图像API:生成、编辑、变体 | 成本较低,支持并发请求,支持图像修复(使用掩码编辑图像) |
| DALL·E 3 | 图像API:仅生成 | 图像质量高于DALL·E 2,支持更大分辨率 |
| GPT Image | 图像API:生成、编辑 - 响应API支持即将推出 | 指令遵循能力更强,文本渲染更好,编辑更精细,具备真实世界知识 |
本指南重点介绍GPT Image,但您也可以切换到DALL·E 2和DALL·E 3的文档。
为确保该模型的负责任使用,在使用gpt-image-1之前,您可能需要从开发者控制台完成API组织验证。
[图片上传失败...(image-a77879-1754112537789)]
生成图像
您可以使用图像生成端点基于文本提示创建图像,或使用响应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 = `
一本儿童绘本中的插画:一位兽医正在用听诊器听水獭宝宝的心跳。
`;
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 = """
一本儿童绘本中的插画:一位兽医正在用听诊器听水獭宝宝的心跳。
"""
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": "一本儿童绘本中的插画:一位兽医正在用听诊器听水獭宝宝的心跳。"
}' | jq -r '.data[0].b64_json' | base64 --decode > otter.png
多轮图像生成
使用响应API,您可以构建涉及图像生成的多轮对话,方法是在上下文中提供图像生成调用输出(也可以只使用图像ID),或使用previous_response_id参数。这使得跨多个轮次迭代图像变得容易——优化提示、应用新指令,并随着对话的进展改进视觉输出。
使用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"));
}
// 后续跟进
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))
# 后续跟进
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"));
}
// 后续跟进
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))
# 后续跟进
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))
效果对比
| 提示 | 效果 |
|---|---|
| "生成一只灰色虎斑猫抱着戴橙色围巾的水獭的图像" | 初始图像 |
| "现在让它看起来更真实" | 优化后图像 |
流式生成
响应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 | 最终图像 |
|---|---|---|
| 初始绘制阶段 | 中间绘制阶段 | 完成绘制 |
优化提示词
在响应API中使用图像生成工具时,主线模型(如gpt-4.1)会自动优化您的提示词以提高性能。
您可以在图像生成调用的revised_prompt字段中访问优化后的提示词:
{
"id": "ig_123",
"type": "image_generation_call",
"status": "completed",
"revised_prompt": "一只灰色虎斑猫抱着一只水獭。水獭戴着橙色围巾。两只动物都很可爱友好,以温暖、温馨的风格描绘。",
"result": "..."
}
编辑图像
图像编辑端点允许您:
- 编辑现有图像
- 使用其他图像作为参考生成新图像
- 通过上传图像和指示应替换区域的掩码来编辑图像的部分内容(称为图像修复)
使用图像参考创建新图像
您可以使用一个或多个图像作为参考来生成新图像。
在这个例子中,我们将使用4个输入图像生成一个包含参考图像中物品的礼品篮新图像。
[图片上传失败...(image-1ed000-1754112537789)][图片上传失败...(image-ac59c2-1754112537789)][图片上传失败...(image-f6ba52-1754112537789)][图片上传失败...(image-c56ab9-1754112537789)]
[图片上传失败...(image-b04533-1754112537789)]
响应API
使用响应API,您可以通过两种不同方式提供输入图像:
- 提供Base64编码的数据URL形式的图像
- 提供文件ID(通过文件API创建)
我们正在积极开发支持将图像文件的完整URL作为输入的功能。
创建文件工具函数
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使用掩码时,会向模型发送额外的指令,以帮助指导相应的编辑过程。
与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": "生成一张相同的阳光室内休息区带泳池的图像,但泳池中应该有一只火烈鸟",
},
{
"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: "生成一张相同的阳光室内休息区带泳池的图像,但泳池中应该有一只火烈鸟",
},
{
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="一个阳光明媚的室内休息区,泳池里有一只火烈鸟"
)
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: "一个阳光明媚的室内休息区,泳池里有一只火烈鸟",
});
// 将图像保存到文件
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=一个阳光明媚的室内休息区,泳池里有一只火烈鸟'
图像修复效果对比
| 原图 | 掩码 | 输出 |
|---|---|---|
| 阳光室内休息区带泳池 | 泳池区域掩码 | 泳池中有火烈鸟的休息区 |
掩码要求
要编辑的图像和掩码必须具有相同的格式和大小(大小小于50MB)。
掩码图像还必须包含alpha通道。如果您使用图像编辑工具创建掩码,请确保将掩码保存为带有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. 将掩码转换为字节
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模型支持高输入保真度,这使您能够更好地保留输出中输入图像的细节。这在使用包含人脸或徽标等元素的图像时特别有用,这些元素需要在生成的图像中准确保留。
您可以提供多个输入图像,所有图像都将以高保真度保留,但请记住,第一个图像将保留更丰富的纹理和更精细的细节,因此如果您包含人脸等元素,请考虑将它们放在第一个图像中。
要启用高输入保真度,请将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、quality和background支持auto选项,模型将根据提示自动选择最佳选项。
尺寸和质量选项
标准质量的正方形图像生成速度最快。默认尺寸为1024x1024像素。
| 可用尺寸 | 1024x1024(正方形)、1536x1024(横向)、1024x1536(纵向)、auto(默认) |
|---|---|
| 质量选项 | low、medium、high、auto(默认) |
输出格式
图像API返回Base64编码的图像数据。默认格式是png,但您也可以请求jpeg或webp。
如果使用jpeg或webp,您还可以指定output_compression参数来控制压缩级别(0-100%)。例如,output_compression=50将把图像压缩50%。
使用jpeg比png更快,因此如果延迟是一个问题,您应该优先选择这种格式。
透明度
gpt-image-1模型支持透明背景。要启用透明度,请将background参数设置为transparent。
它仅支持png和webp输出格式。
透明度在将质量设置为medium或high时效果最佳。
响应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(默认):标准过滤,旨在限制创建某些可能与年龄不适当的内容类别。 -
low:限制性较低的过滤。
支持模型
在响应API中使用图像生成时,支持调用此工具的模型有:
gpt-4ogpt-4o-minigpt-4.1gpt-4.1-minigpt-4.1-nanoo3
成本和延迟
该模型通过首先生成专门的图像令牌来生成图像。延迟和最终成本都与渲染图像所需的令牌数量成正比——更大的图像尺寸和更高的质量设置会产生更多的令牌。
生成的令牌数量取决于图像尺寸和质量:
| 质量 | 正方形(1024×1024) | 纵向(1024×1536) | 横向(1536×1024) |
|---|---|---|---|
| 低 | 272 令牌 | 408 令牌 | 400 令牌 |
| 中 | 1056 令牌 | 1584 令牌 | 1568 令牌 |
| 高 | 4160 令牌 | 6240 令牌 | 6208 令牌 |
请注意,您还需要考虑输入令牌:提示的文本令牌和编辑图像时的输入图像令牌。如果使用高输入保真度,输入令牌的数量将会更高。
有关文本和图像令牌价格的更多信息,请参考我们的定价页面。
因此,最终成本是以下各项的总和:
- 输入文本令牌
- 使用编辑端点时的输入图像令牌
- 图像输出令牌
部分图像成本
如果您想使用partial_images参数流式传输图像生成,每个部分图像将额外产生100个图像输出令牌。
通过本文的介绍,相信您已经对OpenAI图像生成API有了全面的了解。如需开始使用,可通过API中转站快速接入,享受更稳定的服务体验。无论是构建创意工具、电商应用还是内容生成平台,图像生成API都能为您的项目增添强大的视觉生成能力。