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

输出:

相关推荐
新智元11 小时前
毕业 7 年,身价破亿!清北 AI 天团血洗硅谷,奥特曼被逼分天价股份
人工智能·openai
新智元12 小时前
刚刚,苹果大模型团队负责人叛逃 Meta!华人 AI 巨星 + 1,年薪飙至 9 位数
人工智能·openai
掉鱼的猫12 小时前
Java MCP 实战:构建跨进程与远程的工具服务
java·openai·mcp
哪吒编程17 小时前
马斯克掀起"帐篷文化",Grok4即将发布,碾压Gemini 2.5 Pro、Claude Opus 4,国内直接使用
openai·grok
waynaqua18 小时前
FastAPI开发AI应用一:实现连续多轮对话
python·openai
waynaqua18 小时前
FastAPI开发AI应用二:多厂商模型使用指南
python·openai
得帆云低代码1 天前
什么是AI网关?AI网关如何为企业私有化部署筑防
openai
Georgewu2 天前
【AI大模型入门指南】机器学习入门详解
aigc·openai
俞乾2 天前
Context Engineering(上下文工程)是 AI Agent 成功的关键吗?
openai·ai编程
哪吒编程2 天前
写作、编程最强模型Claude Opus 4,碾压o3、Gemini 2.5 Pro,国内直接使用
openai·claude