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

输出:

相关推荐
特立独行的猫a2 天前
OpenAI 函数调用完全指南:让大模型连接外部世界的核心原理
openai·函数调用·mcp·mcpserver
cat2bug6 天前
介绍一下如何在Cat2Bug-Platform中通过OpenAI来创建测试用例
功能测试·测试工具·ai·测试用例·bug·openai
FinClip13 天前
凡泰极客FinClip荣获2025中国企业IT大奖!AI+超级APP重塑企业AI服务
前端·架构·openai
Zeeland13 天前
LangChain——如何选择合适的多智能体架构
ai·langchain·openai·ai agent
石云升13 天前
谁来负责企业落地AI?
aigc·openai·ai编程
草帽lufei14 天前
LangChain 框架基础知识和核心组件Prompts,Chains
langchain·openai·gemini
就这个丶调调15 天前
Python中使用OpenAI实现AI问答:流式返回、记忆存储与工具调用详解
python·openai·流式响应·工具调用·ai问答·记忆存储
SoRound15 天前
【Shopee Games AI 模型使用经验】年度总结之 ------ 识别人脸特征,生成动漫形象
python·openai
草帽lufei16 天前
Prompt Engineering基础实践:角色设定/约束条件等技巧
openai·agent
狼爷16 天前
一文看懂 AI 世界里的新黑话Skills、MCP、Projects、Prompts
人工智能·openai·ai编程