OpenAI nano-banana-2 图片编辑 API 文档
请求地址
https://www.dmxapi.cn/v1/images/edits模型名称
nano-banana-2
Python 代码示例
python
"""
╔═══════════════════════════════════════════════════════════════════════════════╗
║ ║
║ DMXAPI 图文生图工具 (nano-banana-2) ║
║ ║
╠═══════════════════════════════════════════════════════════════════════════════╣
║ ║
║ 功能说明: ║
║ ──────── ║
║ • 使用 DMXAPI 的图片编辑接口,根据原图和文字描述生成 AI 图片 ║
║ • 支持上传图片作为参考,进行智能编辑处理 ║
║ • 生成的图片自动保存到 output 文件夹 ║
║ ║
║ 使用模型: nano-banana-2 ║ ║
║ 接口地址: https://www.dmxapi.cn/v1/images/edits ║
║ ║
╚═══════════════════════════════════════════════════════════════════════════════╝
"""
# ══════════════════════════════════════════════════════════════════════════════
# 依赖导入
# ══════════════════════════════════════════════════════════════════════════════
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/edits"
# ══════════════════════════════════════════════════════════════════════════════
# 图片文件配置
# ══════════════════════════════════════════════════════════════════════════════
# 重要提示 - nano-banana-2 对图片的要求:
# ┌─────────────────────────────────────────────────────────────────┐
# │ • 支持多张图片(最多 16 张) │
# │ • 文件大小:< 50MB │
# │ • 支持格式:png、webp、jpg │
# │ • 尺寸:无限制 │
# └─────────────────────────────────────────────────────────────────┘
image_paths = [
"1.png", # 第一张图片路径
# "/path/to/image2.png", # 第二张图片路径(可选)
# "/path/to/image3.png", # 第三张图片路径(可选)
]
# ══════════════════════════════════════════════════════════════════════════════
# 构建请求参数
# ══════════════════════════════════════════════════════════════════════════════
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": "5:4",
# size: 设置输出图片的分辨率
# - "1K": 1K 分辨率(默认值)
# - "2K": 2K 分辨率
# - "4K": 4K 分辨率
"size": "4k",
# response_format: 设置返回格式
"response_format": "url"
}
# ══════════════════════════════════════════════════════════════════════════════
# HTTP 请求头配置
# ══════════════════════════════════════════════════════════════════════════════
headers = {
"Authorization": f"Bearer {API_KEY}", # 身份验证: Bearer Token 认证方式
}
# ══════════════════════════════════════════════════════════════════════════════
# 主程序执行
# ══════════════════════════════════════════════════════════════════════════════
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: 准备图片文件 │
# │ 遍历配置的图片路径,准备上传文件列表 │
# └─────────────────────────────────────────────────────────────────────────┘
print(f"📷 正在加载图片文件...")
files = []
for img_path in image_paths:
try:
file_name = img_path.split("/")[-1]
mime_type = "image/png" if img_path.lower().endswith(".png") else "image/jpeg"
files.append(
("image", (file_name, open(img_path, "rb"), mime_type))
)
print(f" ✓ 已加载: {img_path}")
except FileNotFoundError:
print(f" ⚠️ 警告: 文件未找到 - {img_path}")
except Exception as e:
print(f" ⚠️ 警告: 处理文件时出错 - {img_path}: {str(e)}")
if not files:
print("❌ 错误: 没有可用的图片文件")
else:
# ┌─────────────────────────────────────────────────────────────────────────┐
# │ 步骤 3: 发送 API 请求 │
# │ 向 DMXAPI 服务器发送 POST 请求,携带图片和编辑参数 │
# └─────────────────────────────────────────────────────────────────────────┘
print(f"📡 正在向 API 发送请求...")
print(f" 模型: {payload['model']}")
print(f" 宽高比: {payload['aspect_ratio']}")
print(f" 分辨率: {payload['size']}")
print(f" 提示词: {payload['prompt']}")
response = requests.post(API_URL, headers=headers, data=payload, files=files)
response.raise_for_status()
# ┌─────────────────────────────────────────────────────────────────────────┐
# │ 步骤 4: 解析 API 响应 │
# │ 将服务器返回的 JSON 数据解析为 Python 字典 │
# └─────────────────────────────────────────────────────────────────────────┘
result = response.json()
print(f"✓ API 响应成功!")
# ┌─────────────────────────────────────────────────────────────────────────┐
# │ 步骤 5: 处理并保存图片 │
# │ 遍历返回的图片数据,解码 Base64 并保存到本地 │
# └─────────────────────────────────────────────────────────────────────────┘
if 'data' in result and len(result['data']) > 0:
print(f"💾 开始保存图片...")
for i, image_data in enumerate(result['data']):
if 'b64_json' in image_data:
base64_data = image_data['b64_json']
image_bytes = base64.b64decode(base64_data)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"edited_{timestamp}_{i+1}.png"
filepath = os.path.join(output_dir, filename)
with open(filepath, 'wb') as f:
f.write(image_bytes)
file_size = os.path.getsize(filepath) / 1024
print(f" ✓ 图片 {i+1}: {filepath} ({file_size:.2f} KB)")
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
📷 正在加载图片文件...
✓ 已加载: 1.png
📡 正在向 API 发送请求...
模型: nano-banana-2
宽高比: 5:4
分辨率: 4k
提示词: 生成一只可爱的小猫
✓ API 响应成功!
💾 开始保存图片...
✓ 图片 1 URL: https://mj-cn.scdn.app/files/gemini/2025/12/15/705307d6-ed15-4a2b-a77d-4be6f84dc49c.png
==================================================
✅ 所有图片处理完成!
==================================================© 2025 DMXAPI nano-banana-2-02 图片编辑
