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

输出:

相关推荐
东小西13 小时前
第6篇:《智能调度中心:当我同时塞给AI查订单、查库存、查物流三个工具》
openai·ai编程
Pokerhead16 小时前
如何评价 OpenAI 的超级对话模型 ChatGPT ?
人工智能·chatgpt·大模型·openai·ai编程
东小西17 小时前
第5篇:《AI学会调接口了:一个@Tool注解让大模型查了今天的天气》
openai·ai编程
小兔子18 小时前
我仿照OpenAI的测试方法,给自己的AI Agent做了个逃逸测试,结果..
openai
Ai拆代码的曹操19 小时前
一篇搞懂 opencode 的三层错误处理架构
openai
怕浪猫20 小时前
第6章 检索增强生成:打造知识库驱动型Agent
openai·agent·ai编程
寅时码1 天前
一次配置,同步到七个 AI CLI【ClaudeCode、Codex、OpenCode...】
openai·ai编程·claude
东小西1 天前
第4篇:《Stream流的浪漫:让AI像ChatGPT一样一个字一个字往外蹦》
openai·ai编程
东小西1 天前
第3篇:《AI的JSON强迫症:我让大模型只回答能解析的格式》
openai·ai编程
东小西2 天前
第2篇:《Prompt不是玄学:我把提示词放到了配置文件里》
openai·ai编程