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

输出:

相关推荐
gujunge2 小时前
Spring with AI (4): 搜索扩展——向量数据库与RAG(上)
ai·大模型·llm·openai·qwen·rag·spring ai·deepseek
机器之心5 小时前
龙虾之后,为什么说「主动式智能」才是Agent的终极形态?
人工智能·openai
机器之心5 小时前
昨晚,OpenClaw大更新,亲手终结「旧插件」时代
人工智能·openai
GoCoding6 小时前
Triton + RISC-V
pytorch·openai·编译器
王小酱8 小时前
从写代码到写规则:如何开发你的 AI 驾驭系统(Harness Engineering 实操指南)
openai·ai编程·aiops
BugShare9 小时前
手撸AI对话助手带上思考过程
openai·ai编程
王小酱11 小时前
私有化 AI Agent 平台进阶指南:智能知识库、Skill 生态与自定义 Agent 实战
openai·ai编程·aiops
王小酱11 小时前
本地部署全能 AI Agent 完整方案
openai·ai编程·aiops
Hilaku13 小时前
数字员工时代:企业级Claw如何让AI成为真正的生产力?
人工智能·openai·agent
超爱柠檬13 小时前
MCP(Model Context Protocol)—— AI 领域的 USB-C
openai·ai编程