OpenAI nano-banana-2 文生图 API 文档
请求地址
https://www.dmxapi.cn/v1/images/generations模型名称
nano-banana-2
Python 代码示例
python
"""
╔═══════════════════════════════════════════════════════════════════════════════╗
║ ║
║ DMXAPI 图片生成工具 (nano-banana-2) ║
║ ║
╠═══════════════════════════════════════════════════════════════════════════════╣
║ ║
║ 功能说明: ║
║ ──────── ║
║ • 使用 DMXAPI 的图片生成接口,根据文字描述生成 AI 图片 ║
║ • 支持多种宽高比和分辨率配置 (1K / 2K / 4K) ║
║ • 生成的图片自动保存到 output 文件夹 ║
║ ║
║ 使用模型: nano-banana-2 ║
║ ║
╚═══════════════════════════════════════════════════════════════════════════════╝
"""
# ══════════════════════════════════════════════════════════════════════════════
# 依赖导入
# ══════════════════════════════════════════════════════════════════════════════
import requests # HTTP 请求库,用于调用 API 接口
import base64 # Base64 编解码,用于处理图片数据
from datetime import datetime # 日期时间处理,用于生成文件名
import os # 操作系统接口,用于文件和目录操作
# ══════════════════════════════════════════════════════════════════════════════
# API 配置
# ══════════════════════════════════════════════════════════════════════════════
API_KEY = "sk-*****************************"
API_URL = "https://www.dmxapi.cn/v1/images/generations"
# ══════════════════════════════════════════════════════════════════════════════
# 构建请求参数
# ══════════════════════════════════════════════════════════════════════════════
payload = {
# 【必填】图像描述
"prompt": "生成一只可爱的小猫",
# 提示词最大长度:32000字符
# 【必填】生图片成数量(只能是1张)
"n": 1,
# 【必填】使用模型
"model": "nano-banana-2",
# aspect_ratio: 设置输出图片的宽高比
#
# ┌─────────────────────────────────────────────────────────────────┐
# │ nano-banana-2 │
# ├──────────┬─────────────────────────────────────────────────────┐│
# │ 宽高比 │ 1K 分辨率 │ 1K令牌 │ 2K 分辨率 │ 4K 分辨率 ││
# ├──────────┼─────────────┼────────┼─────────────┼───────────────┤│
# │ 1:1 │ 1024x1024 │ 1210 │ 2048x2048 │ 4096x4096 ││
# │ 2:3 │ 848x1264 │ 1210 │ 1696x2528 │ 3392x5056 ││
# │ 3:2 │ 1264x848 │ 1210 │ 2528x1696 │ 5056x3392 ││
# │ 3:4 │ 896x1200 │ 1210 │ 1792x2400 │ 3584x4800 ││
# │ 4:3 │ 1200x896 │ 1210 │ 2400x1792 │ 4800x3584 ││
# │ 4:5 │ 928x1152 │ 1210 │ 1856x2304 │ 3712x4608 ││
# │ 5:4 │ 1152x928 │ 1210 │ 2304x1856 │ 4608x3712 ││
# │ 9:16 │ 768x1376 │ 1210 │ 1536x2752 │ 3072x5504 ││
# │ 16:9 │ 1376x768 │ 1210 │ 2752x1536 │ 5504x3072 ││
# │ 21:9 │ 1584x672 │ 1210 │ 3168x1344 │ 6336x2688 ││
# └──────────┴─────────────┴────────┴─────────────┴───────────────┘│
# │ 注: 2K/4K 分辨率令牌分别为 1210/2000 │
# └─────────────────────────────────────────────────────────────────┘
"aspect_ratio": "9:16",
# size: 设置输出图片的分辨率
# - "1K": 1K 分辨率(默认值)
# - "2K": 2K 分辨率
# - "4K": 4K 分辨率
"size": "4k",
# response_format: 设置返回格式
"response_format": "url"
}
# ══════════════════════════════════════════════════════════════════════════════
# HTTP 请求头配置
# ══════════════════════════════════════════════════════════════════════════════
headers = {
"Authorization": f"Bearer {API_KEY}", # 身份验证: Bearer Token 认证方式
"Content-Type": "application/json" # 内容类型: JSON 数据格式
}
# ══════════════════════════════════════════════════════════════════════════════
# 主程序执行
# ══════════════════════════════════════════════════════════════════════════════
try:
print("=" * 50)
print("🎨 开始生成图片...")
print("=" * 50)
# ┌─────────────────────────────────────────────────────────────────────────┐
# │ 步骤 1: 创建输出文件夹 │
# │ 检查 output 目录是否存在,不存在则创建 │
# └─────────────────────────────────────────────────────────────────────────┘
output_dir = "output"
if not os.path.exists(output_dir):
os.makedirs(output_dir)
print(f"✓ 已创建输出文件夹: {output_dir}")
else:
print(f"✓ 输出文件夹已存在: {output_dir}")
# ┌─────────────────────────────────────────────────────────────────────────┐
# │ 步骤 2: 发送 API 请求 │
# │ 向 DMXAPI 服务器发送 POST 请求,携带图片生成参数 │
# └─────────────────────────────────────────────────────────────────────────┘
print(f"📡 正在向 API 发送请求...")
print(f" 模型: {payload['model']}")
print(f" 宽高比: {payload['aspect_ratio']}")
print(f" 分辨率: {payload['size']}")
print(f" 数量: {payload['n']}")
print(f" 提示词: {payload['prompt']}")
response = requests.post(API_URL, json=payload, headers=headers)
response.raise_for_status() # 检查 HTTP 状态码,若有错误则抛出异常
# ┌─────────────────────────────────────────────────────────────────────────┐
# │ 步骤 3: 解析 API 响应 │
# │ 将服务器返回的 JSON 数据解析为 Python 字典 │
# └─────────────────────────────────────────────────────────────────────────┘
result = response.json()
print(f"✓ API 响应成功!")
# ┌─────────────────────────────────────────────────────────────────────────┐
# │ 步骤 4: 处理并保存图片 │
# │ 遍历返回的图片数据,支持 Base64 和 URL 两种格式 │
# └─────────────────────────────────────────────────────────────────────────┘
if 'data' in result and len(result['data']) > 0:
print(f"💾 开始保存图片...")
# ── 遍历返回的每张图片 ──────────────────────────────────────────────────
for i, image_data in enumerate(result['data']):
# ─── 格式 A: Base64 编码图片 (nano-banana-2 / gpt-image-1 返回格式) ───
if 'b64_json' in image_data:
# 解码 Base64 数据为二进制
base64_data = image_data['b64_json']
image_bytes = base64.b64decode(base64_data)
# 生成唯一文件名 (时间戳 + 序号)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"generated_image_{timestamp}_{i+1}.png"
filepath = os.path.join(output_dir, filename)
# 写入图片文件到本地磁盘
with open(filepath, 'wb') as f:
f.write(image_bytes)
# 获取并显示文件大小 (转换为 KB)
file_size = os.path.getsize(filepath) / 1024
print(f" ✓ 图片 {i+1}: {filepath} ({file_size:.2f} KB)")
# ─── 格式 B: URL 链接图片 (dall-e-3 返回格式) ─────────────────────────
elif 'url' in image_data:
print(f" ✓ 图片 {i+1} URL: {image_data['url']}")
# ── 完成提示 ────────────────────────────────────────────────────────────
print(f"{'=' * 50}")
print(f"✅ 所有图片处理完成!")
print(f"{'=' * 50}")
else:
# ── 无数据返回 ──────────────────────────────────────────────────────────
print("❌ 未找到图片数据,请检查 API 响应")
# ══════════════════════════════════════════════════════════════════════════════
# 异常处理
# ══════════════════════════════════════════════════════════════════════════════
except requests.exceptions.RequestException as e:
# ┌─────────────────────────────────────────────────────────────────────────┐
# │ 网络请求异常 │
# │ 包括: 连接超时、DNS 解析失败、HTTP 错误状态码等 │
# └─────────────────────────────────────────────────────────────────────────┘
print(f"{'=' * 50}")
print(f"❌ 请求失败!")
print(f"{'=' * 50}")
print(f"错误信息: {e}")
# 输出详细的错误响应信息 (如果有)
if e.response:
print(f"HTTP 状态码: {e.response.status_code}")
print(f"响应内容: {e.response.text}")
except Exception as e:
# ┌─────────────────────────────────────────────────────────────────────────┐
# │ 其他未知异常 │
# │ 包括: 文件写入错误、JSON 解析错误、编码错误等 │
# └─────────────────────────────────────────────────────────────────────────┘
print(f"{'=' * 50}")
print(f"❌ 发生未知错误!")
print(f"{'=' * 50}")
print(f"错误信息: {e}")返回示例
json
==================================================
🎨 开始生成图片...
==================================================
✓ 输出文件夹已存在: output
📡 正在向 API 发送请求...
模型: nano-banana-2
宽高比: 9:16
分辨率: 4k
数量: 1
提示词: 生成一只可爱的小猫
✓ API 响应成功!
💾 开始保存图片...
✓ 图片 1 URL: https://mj-cn.scdn.app/files/gemini/2025/12/15/31718606-f400-443d-a0d0-ac273bf7dc6d.png
==================================================
✅ 所有图片处理完成!
==================================================© 2025 DMXAPI nano-banana-2-01 文生图
