图片生成接口
NUWA 提供统一的图像生成接口,兼容 OpenAI SDK 和 Gemini SDK。
OpenAI 图像生成
适用模型:
Open AI gpt-image 系列 :
gpt-image-1gpt-image-1.5
Open AI Dall-e 系列 :
dall-e-3gpt-image-1.5
- Python
- JavaScript
- TypeScript
- Curl
from openai import OpenAI
from datetime import datetime
from pathlib import Path
import base64
client = OpenAI(
api_key="API_KEY",
base_url="https://api.nuwaapi.com/v1"
)
response = client.images.generate(
model="dall-e-2",
prompt="High-angle panoramic view of Shanghai Oriental Pearl Tower at twilight, glowing magenta spheres, futuristic Lujiazui skyline background, reflections on Huangpu River, cinematic lighting, hyper-realistic detail.",
size="1024x1024",
n=1,
)
first = response.data[0]
img_b64 = getattr(first, "b64_json", None)
img_url = getattr(first, "url", None)
if img_b64:
Path("openai-image.png").write_bytes(base64.b64decode(img_b64))
print("图片已保存到 openai-image.png")
elif img_url:
print(f"图片 URL:{img_url}(可手动下载)")
else:
print("响应未包含 b64_json 或 url,完整响应:", response)
const fs = require("fs");
async function main() {
const response = await fetch("https://api.nuwaapi.com/v1/images/generations", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "sk-***"
},
body: JSON.stringify({
model: "dall-e-3",
prompt: "High-angle panoramic view of Shanghai Oriental Pearl Tower at twilight, glowing magenta spheres, futuristic Lujiazui skyline background, reflections on Huangpu River, cinematic lighting, hyper-realistic detail.",
size: "1024x1024",
n: 1
})
});
const data = await response.json();
const first = data.data?.[0];
if (first?.b64_json) {
fs.writeFileSync("openai-image.png", Buffer.from(first.b64_json, "base64"));
console.log("图片已保存到 openai-image.png");
} else if (first?.url) {
const imgData = await fetch(first.url).then(r => r.arrayBuffer());
fs.writeFileSync("openai-image.png", Buffer.from(imgData));
console.log("图片已保存到 openai-image.png");
} else {
console.log("完整响应:", JSON.stringify(data, null, 2));
}
}
main().catch(e => console.error("❌ 出错:", e.message));
import OpenAI from "openai";
import fs from "fs";
const client = new OpenAI({
apiKey: "sk-***",
baseURL: "https://api.nuwaapi.com/v1"
});
async function main(): Promise<void> {
const response = await client.images.generate({
model: "dall-e-3",
prompt: "High-angle panoramic view of Shanghai Oriental Pearl Tower at twilight, glowing magenta spheres, futuristic Lujiazui skyline background, reflections on Huangpu River, cinematic lighting, hyper-realistic detail.",
size: "1024x1024",
n: 1
});
const first = response.data[0];
if (first.b64_json) {
fs.writeFileSync("openai-image.png", Buffer.from(first.b64_json, "base64"));
console.log("图片已保存到 openai-image.png");
} else if (first.url) {
const imgData = await fetch(first.url).then(r => r.arrayBuffer());
fs.writeFileSync("openai-image.png", Buffer.from(imgData));
console.log("图片已保存到 openai-image.png");
} else {
console.log("完整响应:", JSON.stringify(response, null, 2));
}
}
main().catch(e => console.error("❌ 出错:", e.message));
#!/bin/bash
# 第一步:请求并保存响应到临时文件
curl https://api.nuwaapi.com/v1/images/generations \
-H "Content-Type: application/json" \
-H "Authorization: sk-***" \
-d '{
"model": "dall-e-3",
"prompt": "High-angle panoramic view of Shanghai Oriental Pearl Tower at twilight, glowing magenta spheres, futuristic Lujiazui skyline background, reflections on Huangpu River, cinematic lighting, hyper-realistic detail.",
"size": "1024x1024",
"n": 1
}' -o response.json
# 第二步:用 Python 处理响应
python -c "
import json, base64
with open('response.json') as f:
data = json.load(f)
first = data['data'][0]
if first.get('b64_json'):
with open('openai-image.png', 'wb') as f:
f.write(base64.b64decode(first['b64_json']))
print('图片已保存到 openai-image.png')
elif first.get('url'):
print('图片 URL:', first['url'])
else:
print('完整响应:', json.dumps(data, indent=2))
"
Gemini 图像生成
适用模型:
Gemini Nano-banana 系列 :
gemini-3-pro-image-previewgemini-2.5-flash-image-preview
- Python
- JavaScript
- TypeScript
- Curl
import base64
import re
from google import genai
from google.genai import types
client = genai.Client(
api_key="API_KEY",
http_options={"base_url": "https://api.nuwaapi.com"},
)
prompt = (
"Da Vinci style anatomical sketch of a dissected Monarch butterfly. "
"Detailed drawings of the head, wings, and legs on textured parchment with notes in English."
)
# 可选参数
aspect_ratio = "1:1" # 支持: "1:1","2:3","3:2","3:4","4:3","4:5","5:4","9:16","16:9","21:9"
resolution = "1K" # 默认1K,支持: "1K", "2K", "4K",注意:必须是大写"K"
response = client.models.generate_content(
model="gemini-3-pro-image-preview",
contents=prompt,
config=types.GenerateContentConfig(
response_modalities=['TEXT', 'IMAGE'],
image_config=types.ImageConfig(
aspect_ratio=aspect_ratio,
image_size=resolution,
),
),
)
# 保存图片 & 输出文本
for part in response.parts:
if part.text:
# 检查是否包含 base64 图片数据
match = re.search(r'data:image/(png|jpeg|jpg|gif|webp);base64,([A-Za-z0-9+/=]+)', part.text)
if match:
image_format = match.group(1)
image_base64 = match.group(2)
image_data = base64.b64decode(image_base64)
filename = f"butterfly.{image_format}"
with open(filename, "wb") as f:
f.write(image_data)
print(f"Image saved: {filename}")
else:
# 普通文本输出
print(part.text)
elif hasattr(part, 'inline_data') and part.inline_data:
with open("butterfly.png", "wb") as f:
f.write(part.inline_data.data)
print("Image saved: butterfly.png (from inline_data)")
const fs = require("fs");
const prompt = "Da Vinci style anatomical sketch of a dissected Monarch butterfly. Detailed drawings of the head, wings, and legs on textured parchment with notes in English.";
async function main() {
const response = await fetch("https://api.nuwaapi.com/v1/models/gemini-3-pro-image-preview:generateContent", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "sk-***"
},
body: JSON.stringify({
contents: [{ parts: [{ text: prompt }] }],
generationConfig: {
responseModalities: ["TEXT", "IMAGE"],
imageConfig: { aspectRatio: "1:1", imageSize: "1K" }
}
})
});
const data = await response.json();
const parts = data?.candidates?.[0]?.content?.parts ?? [];
for (const part of parts) {
if (part.text) {
const match = part.text.match(/data:image\/(png|jpeg|jpg|gif|webp);base64,([A-Za-z0-9+/=]+)/);
if (match) {
const filename = `butterfly.${match[1]}`;
fs.writeFileSync(filename, Buffer.from(match[2], "base64"));
console.log(`Image saved: ${filename}`);
} else {
console.log(part.text);
}
} else if (part.inlineData) {
fs.writeFileSync("butterfly.png", Buffer.from(part.inlineData.data, "base64"));
console.log("Image saved: butterfly.png");
}
}
}
main().catch(e => console.error("❌ 出错:", e.message));
import fs from "fs";
const prompt = "Da Vinci style anatomical sketch of a dissected Monarch butterfly. Detailed drawings of the head, wings, and legs on textured parchment with notes in English.";
async function main(): Promise<void> {
const response = await fetch("https://api.nuwaapi.com/v1/models/gemini-3-pro-image-preview:generateContent", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "sk-***"
},
body: JSON.stringify({
contents: [{ parts: [{ text: prompt }] }],
generationConfig: {
responseModalities: ["TEXT", "IMAGE"],
imageConfig: { aspectRatio: "1:1", imageSize: "1K" }
}
})
});
const data = await response.json();
const parts = data?.candidates?.[0]?.content?.parts ?? [];
for (const part of parts) {
if (part.text) {
const match = part.text.match(/data:image\/(png|jpeg|jpg|gif|webp);base64,([A-Za-z0-9+/=]+)/);
if (match) {
const filename = `butterfly.${match[1]}`;
fs.writeFileSync(filename, Buffer.from(match[2], "base64"));
console.log(`Image saved: ${filename}`);
} else {
console.log(part.text);
}
} else if (part.inlineData) {
fs.writeFileSync("butterfly.png", Buffer.from(part.inlineData.data, "base64"));
console.log("Image saved: butterfly.png");
}
}
}
main().catch(e => console.error("❌ 出错:", e.message));
#!/bin/bash
curl https://api.nuwaapi.com/v1/models/gemini-3-pro-image-preview:generateContent \
-H "Content-Type: application/json" \
-H "Authorization: sk-***" \
-d '{
"contents": [{
"parts": [{
"text": "Da Vinci style anatomical sketch of a dissected Monarch butterfly. Detailed drawings of the head, wings, and legs on textured parchment with notes in English."
}]
}],
"generationConfig": {
"responseModalities": ["TEXT", "IMAGE"],
"imageConfig": {
"aspectRatio": "1:1",
"imageSize": "1K"
}
}
}' -o response.json
python -c "
import json, base64, re
with open('response.json') as f:
data = json.load(f)
for part in data.get('candidates', [{}])[0].get('content', {}).get('parts', []):
if 'text' in part:
match = re.search(r'data:image/(png|jpeg|jpg|gif|webp);base64,([A-Za-z0-9+/=]+)', part['text'])
if match:
ext, b64 = match.group(1), match.group(2)
with open(f'butterfly.{ext}', 'wb') as f:
f.write(base64.b64decode(b64))
print(f'Image saved: butterfly.{ext}')
else:
print(part['text'])
elif 'inlineData' in part:
with open('butterfly.png', 'wb') as f:
f.write(base64.b64decode(part['inlineData']['data']))
print('Image saved: butterfly.png')
"