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

输出:

相关推荐
用户479492835691513 小时前
[开源分享] Agent 指挥 Agent,我做了一个让 Claude Code / Codex / Gemini/... 组成"军团"并行干活的工具
aigc·openai·claude
王小酱16 小时前
Everything Claude Code 完全长篇指南
openai·ai编程·aiops
用户479492835691516 小时前
像 Tech Lead 一样管理 AI Agent:一条命令,并行执行,交叉验证
aigc·openai·agent
树獭叔叔16 小时前
06-大模型如何"学习":从梯度下降到AdamW优化器
后端·aigc·openai
王小酱17 小时前
Everything Claude Code 速查指南
openai·ai编程·aiops
FinClip1 天前
财富管理奇点已到:AI让投资顾问以一当百
openai
ssshooter2 天前
免费和付费 AI API 选择指南
人工智能·aigc·openai
机器之心2 天前
击败谷歌、英伟达!清华陈建宇×斯坦福Chelsea团队世界模型Ctrl-World具身能力登顶全球
人工智能·openai
AI袋鼠帝2 天前
阿里出手了!终于不怕OpenClaw烧token啦,直接算力自由~
openai
树獭叔叔2 天前
05-从隐藏向量到文字:LM Head如何输出"下一个词"?
后端·aigc·openai