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

输出:

相关推荐
就这个丶调调20 小时前
Python中使用OpenAI实现AI问答:流式返回、记忆存储与工具调用详解
python·openai·流式响应·工具调用·ai问答·记忆存储
SoRound1 天前
【Shopee Games AI 模型使用经验】年度总结之 ------ 识别人脸特征,生成动漫形象
python·openai
草帽lufei2 天前
Prompt Engineering基础实践:角色设定/约束条件等技巧
openai·agent
狼爷2 天前
一文看懂 AI 世界里的新黑话Skills、MCP、Projects、Prompts
人工智能·openai·ai编程
黄林晴2 天前
Anthropic 发布 Cowork:让 AI 成为你的「虚拟同事」
openai·ai编程·vibecoding
杜余生2 天前
我的 Claude Code 安装使用体验分享
openai
机器之心3 天前
2026年,大模型训练的下半场属于「强化学习云」
人工智能·openai
黄林晴3 天前
这个官方插件能让你的"屎山代码"焕然一新
aigc·openai·ai编程
XinZong3 天前
【Claude】获取Claude API Key的多种方式全攻略:从入门到精通,再到详解教程!(claude-3.5-haiku-20241022)
openai·claude
草帽lufei4 天前
OpenAI API调用实践文本分类和内容生成
openai·agent