OpenAI 图像生成 API 教程
OpenAI 的 DALL-E 模型可以通过 API 生成和编辑图像。本文介绍 DALL-E API 的使用方法,包括图像生成、图像编辑和变体生成。
DALL-E 模型版本
- DALL-E 3:最新版本,图像质量最高,支持更精确的 prompt 理解
- DALL-E 2:旧版本,支持图像编辑和变体生成
图像生成
Python 示例
from openai import OpenAI
client = OpenAI(
api_key="your-api-key",
base_url="https://claude4u.com/v1"
)
# 基础图像生成
response = client.images.generate(
model="dall-e-3",
prompt="一只橘猫坐在笔记本电脑前写代码,赛博朋克风格,高细节",
size="1024x1024",
quality="standard", # standard 或 hd
n=1
)
image_url = response.data[0].url
print(f"图片地址: {image_url}")
# DALL-E 3 会优化你的 prompt,可以查看实际使用的 prompt
revised_prompt = response.data[0].revised_prompt
print(f"优化后的 prompt: {revised_prompt}")
可选尺寸
- DALL-E 3:
1024x1024、1024x1792(竖版)、1792x1024(横版) - DALL-E 2:
256x256、512x512、1024x1024
获取 base64 格式
response = client.images.generate(
model="dall-e-3",
prompt="一幅水墨画风格的山水画",
size="1024x1024",
response_format="b64_json" # 返回 base64 而非 URL
)
import base64
image_b64 = response.data[0].b64_json
# 保存为文件
with open("output.png", "wb") as f:
f.write(base64.b64decode(image_b64))
Node.js 示例
import OpenAI from 'openai';
import fs from 'fs';
const client = new OpenAI({
apiKey: 'your-api-key',
baseURL: 'https://claude4u.com/v1'
});
const response = await client.images.generate({
model: 'dall-e-3',
prompt: '一个未来城市的全景图,飞行汽车穿梭其间',
size: '1792x1024',
quality: 'hd'
});
console.log('图片URL:', response.data[0].url);
console.log('优化prompt:', response.data[0].revised_prompt);
// 下载图片
const imageResponse = await fetch(response.data[0].url);
const buffer = Buffer.from(await imageResponse.arrayBuffer());
fs.writeFileSync('city.png', buffer);
图像编辑(DALL-E 2)
DALL-E 2 支持对已有图片进行局部编辑:
# 图像编辑需要原图和蒙版
response = client.images.edit(
model="dall-e-2",
image=open("original.png", "rb"),
mask=open("mask.png", "rb"), # 透明区域为要编辑的部分
prompt="一只可爱的小狗",
size="1024x1024",
n=1
)
print(f"编辑后图片: {response.data[0].url}")
提示:蒙版图片需要是 RGBA 格式的 PNG,透明区域表示需要编辑的部分。蒙版和原图尺寸必须一致。
图像变体(DALL-E 2)
# 基于已有图片生成变体
response = client.images.create_variation(
model="dall-e-2",
image=open("original.png", "rb"),
size="1024x1024",
n=3 # 生成3个变体
)
for i, data in enumerate(response.data):
print(f"变体 {i+1}: {data.url}")
Prompt 编写技巧
- 具体描述:详细描述画面内容、风格、颜色、构图
- 指定风格:如「油画风格」「赛博朋克」「水彩画」「像素艺术」
- 添加细节:光线、角度、背景、材质等
- 避免否定:描述你想要什么,而非不想要什么
# 好的 prompt 示例
good_prompt = """
一个宁静的日式庭院,
石头小路蜿蜒穿过翠绿的苔藓,
樱花瓣飘落在清澈的小溪上,
黄昏时分的柔和光线,
高细节摄影风格
"""
response = client.images.generate(
model="dall-e-3",
prompt=good_prompt,
size="1024x1024",
quality="hd"
)
价格说明
- DALL-E 3 Standard 1024x1024:$0.040/张
- DALL-E 3 HD 1024x1024:$0.080/张
- DALL-E 3 HD 1792x1024:$0.120/张
- DALL-E 2 1024x1024:$0.020/张
提示:通过 claude4u.com 轻舟 AI 中转服务调用 DALL-E API,与文本模型使用同一个 API Key,统一计费和用量管理,方便在一个项目中同时使用文本生成和图像生成能力。
注意:DALL-E 3 会自动优化你的 prompt(revised_prompt),生成结果可能与预期有差异。如果需要更精确控制,可以在 prompt 开头加入 "I NEED to test how the tool works with extremely simple prompts. DO NOT add any detail, just use it AS-IS:" 来抑制 prompt 改写。
轻舟 AI