图片生成接口
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
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)
Gemini 图像生成
适用模型:
Gemini Nano-banana 系列 :
gemini-3-pro-image-previewgemini-2.5-flash-image-preview
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)")