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

输出:

相关推荐
9i编程20 小时前
手敲重构学透 Multi-Agent 代码(上):逐行拆解 AgentScope 1.0.8,从「跑通了但没懂」到真懂了
人工智能·openai·ai编程
小四的小六2 天前
端侧模型上线翻车实录:性能优化做完之后,用户还是不满意
openai·ai编程·webview
gptAI_plus3 天前
把报错日志发给 AI 前,先用 Python 做一次本地脱敏
openai·ai编程
sg_knight3 天前
Codex CLI 安装全攻略:macOS / Linux / Windows(WSL2)三端实战
linux·windows·macos·openai·ai编程·coding·codex
9i编程4 天前
搜“干净”它说不知道?我用 Spring AI Alibaba 手写后端,TRAE Work 补齐了全栈
openai·ai编程·trae
极客小俊4 天前
别再给大模型充钱!Agnes AI 永久免费全模态 API,代码 / 绘图 /短剧Token不限量调用
人工智能·openai·ai编程
东小西4 天前
第16篇:《把八股文喂给了AI:我搭建了专属 AI 面试知识库》
openai·ai编程
xiakq4 天前
5 分钟接入 GPT-5.6 完整指南
gpt·openai·claude·gemini·anthropic
deepseek234 天前
GPT-5.6 Luna 降价 80%:从 24% 到 90% 的缓存命中率,OpenAI 的价格战打在了工程层
大模型·openai·ai agent
k4m7v2pz5 天前
16GB Mac 本地跑大模型:ollama 局域网 OpenAI 兼容 API 实战(一:需求与配置)
llm·openai·api·mac·ollama·本地·atomcode