调用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()

输出:

相关推荐
怕浪猫5 小时前
2026年为什么我推荐你学DeepSeek Harness?AI Agent开发入门指南
openai·agent·ai编程
怕浪猫7 小时前
从 pre-execute 到 post-execute:AI Agent 调用工具时背后发生了什么
aigc·openai·ai编程
爱吃的小肥羊13 小时前
ChatGPT Pro 额度被爆缩水 77%,OpenAI 被喷惨了!
openai
全栈弄潮儿14 小时前
一周总结:把 AI 当助手,而不是答案机器
aigc·openai·ai编程
怕浪猫1 天前
一行行拆解 agent-loop:AI Agent 的"思考循环"到底是怎么转的
aigc·openai·agent
9i编程1 天前
4. AI编写的SKILL,坑我一一试过,这次我自己改写:换个工具,照样不按SKILL写文档
人工智能·openai·ai编程
掘金酱2 天前
Vibe作品广场首发挑战来啦!发布作品,赢富士拍立得等千元好礼
openai·ai编程·vibecoding
全栈弄潮儿2 天前
代码报错怎么办?正确使用 AI 排查错误
aigc·openai·ai编程
花椒技术2 天前
别再把 SOP 直接丢给 Agent 了,它真的看不懂
openai·agent·ai编程
殷紫川3 天前
DeepSeek Harness :当"一切皆插件"成为 Agent 的新底座
openai·ai编程·deepseek