调用DALL·E-3 API生成图片

python 复制代码
import base64
import matplotlib.pyplot as plt
from openai import OpenAI
from PIL import Image
from io import BytesIO

api_key = "sk-xxxxx"

def base64_to_image(base64_string):
    try:
        image_data = base64.b64decode(base64_string)
        image_buffer = BytesIO(image_data)
        image = Image.open(image_buffer)
        return image
    except Exception as e:
        print(f"An error occurred: {e}")
        return None

client = OpenAI(api_key=api_key)
response = client.images.generate(
    model="dall-e-3",
    prompt="A spaceship flying through the universe", # an example
    size="1024x1024",
    quality="standard",
    n=1,
    response_format='b64_json'
)

image_b64 = response.data[0].b64_json
generated_image = base64_to_image(image_b64)

if generated_image:
	plt.imshow(generated_image)
	plt.axis("off")
	plt.show()

输出:

相关推荐
johnsong3 小时前
AI前沿日报 · 2026-11-27:超人优化器、推理账单与 Rust 重写
rust·openai·anthropic·黎曼猜想·数学优化·ai前沿日报·gpt-6.2
沉默王二3 天前
赶在老黄回归前,GLM-5.4 发布了。
openai·agent·chatglm (智谱)
2601_967979123 天前
OpenAI创始成员发布开源项目nanochat,仅需100美元就能实现类ChatGPT
chatgpt·openai·llm训练·nanochat·安德烈·卡帕西
沉默王二4 天前
谷歌真争气啊,这下可以爽用Gemini了。
openai·agent·gemini
Summer-Bright5 天前
深度 | 智能体记忆被「收编」:OpenAI 会做梦,Claude 合并记忆,中间件两头承压
中间件·openai·记忆·anthropic
Thanks_ks6 天前
AI Agent 开发入门:用 Function Calling 让大模型学会 “动手干活”,附订单查询机器人实战
python·ai·大模型·openai·agent·通义千问·mcp
学无止境小袁同学8 天前
OpenAI Agents SDK 模板操作手册(可直接操作)
大模型·openai·agent·sdk·大模型应用
沉默王二8 天前
腾讯这波上大分,Hy4-flash值得你猛蹬。
openai·agent·vibecoding
可夫小子8 天前
OpenAI 用 Codex 修 ChatGPT 性能,1700 次调查只直接合入 15 个 PR
openai·ai编程
ZzT10 天前
GPT-6.2 API 降价 20%,为什么老代码直接切过去反而更费钱?
openai·ai编程