GPT-Image-2 API 接入实战:Python 调用 3 分钟搞定,附完整可运行代码(2026)

5 阅读6分钟

好多朋友找到我说,大霖,GPT-Image-2 这个图片生成模型到底怎么调 API?官方文档看得头大,代码跑不通,Key 还申请不下来。行,今天我把这事儿一次性说清楚。

GPT-Image-2 是 OpenAI 2026 年推出的最新图片生成模型,通过兼容 OpenAI 协议的 API 即可调用。整个流程就三步:注册拿 Key、了解接口参数、跑通 Python 代码。我自己实测下来,从注册到第一张图片生成出来,真就 3 分钟。下面是完整的保姆级教程,代码直接复制就能跑。

先说结论

项目说明
模型名称gpt-image-2
调用方式OpenAI Images API(/v1/images/generations
核心参数promptsizenquality
返回格式Base64 编码或 URL
生成耗时实测 5-15 秒(取决于分辨率和 quality)
失败扣费不扣,生成失败不计费
并发限制聚合接口无并发限制

第一步:注册拿 Key

这步最简单。ofox.ai 是一个 AI 模型聚合平台,一个 API Key 可以调用 GPT-5、Claude Opus 4.6、Gemini 3、GPT-Image-2 等 50+ 模型,支持支付宝/微信付款,按量计费免费版可起步。

操作流程:

  1. 打开 [ofox.ai](ofox.ai?utm_source=juejin&utm_medium=yuxiaqianshou_article&utm_campaign=seo),支付宝/微信直接注册
  2. 进入控制台 → API Keys → 创建新 Key
  3. 复制保存好这个 Key,后面代码里要用

不用折腾信用卡,不用填地址。拿到 Key 就可以开干了。

第二步:接口参数详解

GPT-Image-2 走的是标准的 OpenAI Images API,核心参数就这几个:

参数类型必填说明
modelstring固定填 gpt-image-2
promptstring图片描述,越具体效果越好
ninteger生成数量,默认 1,最多 4
sizestring分辨率:1024x1024(默认)、1536x10241024x1536
qualitystringlowmediumhigh,默认 medium
response_formatstringurlb64_json,默认 url

几个注意点(我踩过的坑):

  • prompt 写英文效果明显好于中文,中文也能用但偶尔会出现文字渲染错乱
  • size 只支持上面三个值,传 512x512 之类的会直接报错
  • qualityhigh 生成时间会翻倍,但确实细节更好
  • response_format 建议用 b64_json,URL 方式返回的链接有效期只有 1 小时
graph LR
 A[你的 Python 代码] -->|POST /v1/images/generations| B[ofox.ai 聚合网关]
 B --> C[GPT-Image-2 模型]
 C -->|返回 Base64/URL| B
 B -->|响应| A
 A --> D[保存为本地图片]

第三步:完整可运行的 Python 代码

方案一:同步调用(最简单)

适合生成单张图片,代码最少:

import base64
import os
from openai import OpenAI

# 初始化客户端
client = OpenAI(
 api_key="your-ofox-api-key", # 替换成你在 ofox.ai 拿到的 Key
 base_url="https://api.ofox.ai/v1"
)

def generate_image(prompt: str, size: str = "1024x1024", quality: str = "medium"):
 """同步生成图片,返回本地文件路径"""
 print(f"正在生成图片: {prompt[:50]}...")
 
 response = client.images.generate(
 model="gpt-image-2",
 prompt=prompt,
 n=1,
 size=size,
 quality=quality,
 response_format="b64_json"
 )
 
 # 解码 Base64 并保存
 image_data = base64.b64decode(response.data[0].b64_json)
 output_path = "output.png"
 with open(output_path, "wb") as f:
 f.write(image_data)
 
 print(f"图片已保存到: {output_path}")
 return output_path


# 直接运行
if __name__ == "__main__":
 generate_image(
 prompt="A cute robot sitting at a desk writing Python code, digital art style, warm lighting",
 size="1024x1024",
 quality="high"
 )

跑一下试试,正常情况下 5-10 秒就能在当前目录看到 output.png

方案二:提交 + 轮询(适合批量生成)

说实话方案一够用了,但如果你要批量生成图片,或者想做个异步的图片生成服务,用提交+轮询的方式更靠谱。好处是不会因为网络超时而丢失任务:

import base64
import time
import requests
import os

API_KEY = "your-ofox-api-key" # 替换成你的 Key
BASE_URL = "https://api.ofox.ai/v1"

HEADERS = {
 "Authorization": f"Bearer {API_KEY}",
 "Content-Type": "application/json"
}


def submit_image_task(prompt: str, size: str = "1024x1024", quality: str = "medium"):
 """提交图片生成任务"""
 payload = {
 "model": "gpt-image-2",
 "prompt": prompt,
 "n": 1,
 "size": size,
 "quality": quality,
 "response_format": "b64_json"
 }
 
 resp = requests.post(
 f"{BASE_URL}/images/generations",
 headers=HEADERS,
 json=payload,
 timeout=60
 )
 
 if resp.status_code == 200:
 return resp.json()
 else:
 print(f"提交失败: {resp.status_code} - {resp.text}")
 return None


def poll_and_save(prompt: str, output_path: str = "output.png", 
 max_retries: int = 3, size: str = "1024x1024", quality: str = "medium"):
 """带重试的图片生成:提交 + 轮询检查 + 保存"""
 for attempt in range(1, max_retries + 1):
 print(f"第 {attempt} 次尝试生成...")
 
 try:
 result = submit_image_task(prompt, size=size, quality=quality)
 
 if result and "data" in result and len(result["data"]) > 0:
 b64_str = result["data"][0].get("b64_json")
 
 if b64_str:
 image_data = base64.b64decode(b64_str)
 with open(output_path, "wb") as f:
 f.write(image_data)
 print(f"生成成功!已保存到: {output_path}")
 return output_path
 
 # 如果返回的是 URL
 url = result["data"][0].get("url")
 if url:
 print(f"拿到图片 URL: {url}")
 img_resp = requests.get(url, timeout=30)
 with open(output_path, "wb") as f:
 f.write(img_resp.content)
 print(f"生成成功!已保存到: {output_path}")
 return output_path
 
 print(f"第 {attempt} 次未拿到有效结果,等待 3 秒后重试...")
 time.sleep(3)
 
 except requests.exceptions.Timeout:
 print(f"第 {attempt} 次请求超时,等待 5 秒后重试...")
 time.sleep(5)
 except Exception as e:
 print(f"第 {attempt} 次出错: {e},等待 3 秒后重试...")
 time.sleep(3)
 
 print("达到最大重试次数,生成失败")
 return None


def batch_generate(prompts: list, output_dir: str = "outputs"):
 """批量生成多张图片"""
 os.makedirs(output_dir, exist_ok=True)
 results = []
 
 for i, prompt in enumerate(prompts):
 output_path = os.path.join(output_dir, f"image_{i+1}.png")
 print(f"\n--- 生成第 {i+1}/{len(prompts)} 张 ---")
 
 path = poll_and_save(
 prompt=prompt,
 output_path=output_path,
 max_retries=3,
 quality="medium"
 )
 results.append({"prompt": prompt, "path": path, "success": path is not None})
 
 # 每张之间歇 1 秒,别太猛
 if i < len(prompts) - 1:
 time.sleep(1)
 
 # 打印汇总
 success_count = sum(1 for r in results if r["success"])
 print(f"\n=== 批量生成完成:{success_count}/{len(prompts)} 成功 ===")
 return results


# 运行示例
if __name__ == "__main__":
 # 单张生成
 poll_and_save(
 prompt="A futuristic city skyline at sunset, cyberpunk style, neon lights reflecting on wet streets",
 output_path="cyberpunk_city.png",
 quality="high"
 )
 
 # 批量生成
 prompts = [
 "A minimalist logo design for a tech startup, clean lines, blue and white",
 "An isometric illustration of a cozy home office with plants and a cat",
 "A watercolor painting of a mountain lake at dawn, soft colors",
 ]
 batch_generate(prompts)

这段代码包含了完整的错误处理、超时重试、批量生成逻辑,直接复制到项目里就能用。

踩坑记录

说几个我实际遇到的坑,帮你们省点时间:

坑 1:中文 prompt 里带引号导致 JSON 解析失败

我一开始直接把用户输入的中文丢进去,结果有人输入了带 " 的内容,requests 序列化没问题但服务端解析炸了。解决方案:用 json 库自己序列化一遍,或者干脆用 openai SDK(方案一),SDK 内部会处理好。

坑 2:quality=high + 1536x1024 偶尔超时

高分辨率加高质量的组合,生成时间可能到 20-30 秒。你的 timeout 设太短就会断掉。建议 timeout 至少设 60 秒,或者用方案二的重试逻辑兜底。

坑 3:URL 返回格式的链接过期

前面提了,response_format="url" 返回的链接只有 1 小时有效期。我之前做了个图片生成服务,把 URL 直接存数据库了,结果第二天用户一刷新全是 404。老老实实用 b64_json,拿到就存本地或者传 OSS。

坑 4:prompt 太短效果很差

"一只猫" 这种 prompt 出来的图基本没法看。GPT-Image-2 吃细节描述,建议至少写 20-30 个词,包含主体、风格、光线、构图这些信息。英文效果好于中文。

小结

整个流程捋一遍:

  1. ofox.ai 注册拿 Key(1 分钟)
  2. 搞清楚 promptsizequality 这几个核心参数(1 分钟)
  3. 把上面的代码复制过去,改一下 Key 和 prompt 就能跑(1 分钟)

生成失败不扣钱,聚合接口也没有并发限制,放心大胆地试。我自己现在做的一个小工具就是用 GPT-Image-2 批量生成产品图,一天跑几百张,稳得很。

想试试的直接去 [ofox.ai](ofox.ai?utm_source=juejin&utm_medium=yuxiaqianshou_article&utm_campaign=seo) 注册个账号,免费额度够你把上面的代码全跑一遍了。