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

输出:

相关推荐
serendipity73311 小时前
一文带你彻底掌握Function Call 的使用(nodejs版)
openai
机器之心12 小时前
太强了!DeepSeek刚刚开源新模型,用视觉方式压缩一切
人工智能·openai
机器之心14 小时前
Meta用40万个GPU小时做了一个实验,只为弄清强化学习Scaling Law
人工智能·openai
_清欢l15 小时前
搭建Dify
openai
AntBlack1 天前
虽迟但到 :盘一盘 SpringAI 现在发展得怎么样了?
后端·spring·openai
叶庭云1 天前
一文掌握 CodeX CLI 安装以及使用!
人工智能·openai·安装·使用教程·codex cli·编码智能体·vibe coding 终端
数据智能老司机2 天前
使用 OpenAI Agents SDK 构建智能体——记忆与知识
llm·openai·agent
数据智能老司机2 天前
使用 OpenAI Agents SDK 构建智能体——代理工具与 MCP
llm·openai·agent
Larcher3 天前
n8n 入门笔记:用零代码工作流自动化重塑效率边界
前端·openai
七牛云行业应用3 天前
从API调用到智能体编排:GPT-5时代的AI开发新模式
大数据·人工智能·gpt·openai·agent开发