Skip to content

Gemini 图片编辑 API 接口文档

使用 Gemini(又称 Nano Banana 🍌)模型进行智能图片编辑

接口地址

https://www.dmxapi.cn

注意:

需要升级谷歌sdk为最新版

模型名称

模型名称说明
gemini-3-pro-image-preview支持 1K/2K/4K 分辨率的高级图像编辑模型
gemini-2.5-flash-image支持 1K 分辨率的快速图像编辑模型

Python SDK 代码示例

以下示例展示了如何使用 DMXAPI 调用 Gemini 模型进行图片编辑:

python

"""
DMXAPI Gemini 图像修改示例
使用 Google Gemini API 修改图像,并保存到本地 output 文件夹
"""

from google import genai
from google.genai import types
from PIL import Image
import os
from datetime import datetime

# ============================================================================
# 配置部分
# ============================================================================

# DMXAPI 密钥和基础 URL
api_key = "sk-*******************************************"  # 替换为你的 DMXAPI 密钥
BASE_URL = "https://www.dmxapi.cn"

# 输入图像路径
INPUT_IMAGE_PATH = "test/example.jpg"  # 替换为你要修改的图片路径

# 创建 Gemini 客户端
client = genai.Client(api_key=api_key, http_options={'base_url': BASE_URL})

# ============================================================================
# 图像修改提示词
# ============================================================================

# 读取要修改的图像
image = Image.open(INPUT_IMAGE_PATH)

# 定义图像修改的提示词
prompt = (
    "让这个计算器吃西瓜"
)

# ============================================================================
# 调用 DMXAPI 修改图像
# ============================================================================

response = client.models.generate_content(
    # 模型名称
    model="gemini-3-pro-image-preview",  # 使用 Gemini 2.5 Flash 图像模型

    # 输入内容:提示词 + 原始图像
    contents=[prompt, image],

    # 生成配置
    config=types.GenerateContentConfig(
        # response_modalities: 设置响应模态
        # - ['Image']: 仅返回图片,不返回文本
        # - ['Text', 'Image']: 同时返回文本和图片(默认值)
        # gemini-2.5-flash-image 不能使用该参数
        response_modalities=['Image'],

        # image_config: 图像配置选项
        image_config=types.ImageConfig(
            # aspect_ratio: 设置输出图片的宽高比(注意:使用驼峰命名)
            #
            # ┌─────────────────────────────────────────────────────────────────┐
            # │ Gemini 2.5 Flash                                                │
            # ├──────────┬─────────────┬────────┐                               │
            # │ 宽高比    │ 分辨率      │ 令牌    │                               │
            # ├──────────┼─────────────┼────────┤                               │
            # │ 1:1      │ 1024x1024   │ 1290   │                               │
            # │ 2:3      │ 832x1248    │ 1290   │                               │
            # │ 3:2      │ 1248x832    │ 1290   │                               │
            # │ 3:4      │ 864x1184    │ 1290   │                               │
            # │ 4:3      │ 1184x864    │ 1290   │                               │
            # │ 4:5      │ 896x1152    │ 1290   │                               │
            # │ 5:4      │ 1152x896    │ 1290   │                               │
            # │ 9:16     │ 768x1344    │ 1290   │                               │
            # │ 16:9     │ 1344x768    │ 1290   │                               │
            # └──────────┴─────────────┴────────┘                               │
            # └─────────────────────────────────────────────────────────────────┘
            #
            # ┌─────────────────────────────────────────────────────────────────┐
            # │ Gemini 3 Pro Image 预览版                                        │
            # ├──────────┬─────────────────────────────────────────────────────┐│
            # │ 宽高比    │ 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="16:9",

            # image_size: 设置输出图片的分辨率
            # - "1K": 1K 分辨率(默认值,所有模型均支持)
            # - "2K": 2K 分辨率(仅 Gemini 3 Pro Image 预览版支持)
            # - "4K": 4K 分辨率(仅 Gemini 3 Pro Image 预览版支持)
            # gemini-2.5-flash-image 不能使用该参数
            # image_size="4K",
        ),

        # tools: Google 搜索工具(可选)
        # - 使用实时信息修改图像(如根据最新资讯添加元素等)
        # - 注意: 使用搜索工具时必须设置 response_modalities=['Text', 'Image']
        # - 图片专用模式 ['Image'] 与搜索工具不兼容
        # 示例: tools=[{"google_search": {}}]
        # gemini-2.5-flash-image 不能使用该参数
        # tools=[{"google_search": {}}]
    )
)

# ============================================================================
# 处理响应并保存修改后的图像
# ============================================================================

for part in response.parts:
    # 处理文本响应(如果有)
    if part.text is not None:
        print(part.text)

    # 处理图像响应
    elif part.inline_data is not None:
        # 确保 output 文件夹存在
        os.makedirs("output", exist_ok=True)

        # 生成带时间戳的文件名
        # 格式: edited_image_20250121_143052.png (年月日_时分秒)
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = f"output/edited_image_{timestamp}.png"

        # 将响应数据转换为 PIL Image 对象
        image = part.as_image()

        # 保存图像到文件
        image.save(filename)

        # 输出保存成功的提示信息
        print(f"修改后的图片已保存到 {filename}")

运行结果

执行上述代码后,你将看到类似以下的输出:

json
**Visualizing a Calculator**

I'm currently picturing a calculator, specifically a Canon WS-1212H model, as a cartoon character. I'm focusing on giving it a face and limbs. The primary action is having it enjoy a watermelon. I'm working out the best way to incorporate the watermelon into the design, perhaps using the calculator's display as the mouth.



**Designing the Scene**

I've decided on the scene: the calculator is holding the watermelon. I'm focusing on the details of the watermelon itself – the red flesh, the black seeds. I'm imagining juice and rind around the calculator's mouth. I'm considering how to arrange the discarded rinds and seeds in the scene. The original blue wave background will be kept.



**Visualizing the Concept**

I'm currently focused on the anthropomorphic aspects, specifically how to best represent a calculator enjoying watermelon. The details of the watermelon itself, from the juice to the rind, are areas I'm carefully considering for the most impactful visual representation.



**Evaluating the Results**

I've reviewed the output and focused on the anthropomorphic elements. The successful cartoonization of the calculator, combined with the action and details, aligns with the specified goals. The depiction of the watermelon and the calculator's expression are noteworthy.



修改后的图片已保存到 output/edited_image_20251121_182350.png

Python request 代码示例

python
"""
================================================================
Gemini 图文生图示例
================================================================
功能说明:
    使用 Google Gemini API 的接口,根据文字提示词和输入图片生成新图片。
    支持调整输出图片的比例、大小,以及调用谷歌搜索工具。
================================================================
"""
import requests
import base64
import os
from datetime import datetime

# ========================================
# API 配置信息
# ========================================
# 你的 DMXAPI 密钥(请替换为真实密钥)
API_KEY = "sk-********************************"

# DMXAPI 请求地址
BASE_URL = "https://www.dmxapi.cn/v1beta"

# ========================================
# 图片配置
# ========================================
# 输入图片路径
INPUT_IMAGE_PATH = "gemini-native-image.png"

# ========================================
# 图片编码函数
# ========================================
def encode_image_to_base64(image_path: str) -> tuple[str, str]:
    """读取图片文件并转换为 base64 编码"""
    ext = os.path.splitext(image_path)[1].lower()
    mime_types = {
        '.jpg': 'image/jpeg',
        '.jpeg': 'image/jpeg',
        '.png': 'image/png',
        '.gif': 'image/gif',
        '.webp': 'image/webp',
    }
    mime_type = mime_types.get(ext, 'image/jpeg')

    with open(image_path, 'rb') as f:
        image_data = f.read()

    return base64.b64encode(image_data).decode('utf-8'), mime_type

# ========================================
# 构建请求头
# ========================================
headers = {
    "Content-Type": "application/json",
    "x-goog-api-key": API_KEY,
}

# ========================================
# 构建请求体
# ========================================
# 编码图片为 base64
img_base64, mime_type = encode_image_to_base64(INPUT_IMAGE_PATH)

payload = {
    "model": "gemini-3-pro-image-preview",                          # 指定使用的 AI 模型
    "contents": [{
        "parts": [
            {"text": "在图像中加入梵高的自画像"},
            {
                "inline_data": {
                    "mime_type": mime_type,
                    "data": img_base64
                }
            }
        ]
    }],
    "generationConfig": {
        # responseModalities: 设置响应模态
        # - ['IMAGE']: 仅返回图片,不返回文本
        # - ['TEXT', 'IMAGE']: 同时返回文本和图片(默认值)
        "responseModalities": ["IMAGE"],

        # imageConfig: 图像配置选项
        "imageConfig": {
            # aspectRatio: 设置输出图片的宽高比
            #
            # ┌─────────────────────────────────────────────────────────────────┐
            # │ Gemini 2.5 Flash                                                │
            # ├──────────┬─────────────┬────────┐                               │
            # │ 宽高比    │ 分辨率      │ 令牌    │                               │
            # ├──────────┼─────────────┼────────┤                               │
            # │ 1:1      │ 1024x1024   │ 1290   │                               │
            # │ 2:3      │ 832x1248    │ 1290   │                               │
            # │ 3:2      │ 1248x832    │ 1290   │                               │
            # │ 3:4      │ 864x1184    │ 1290   │                               │
            # │ 4:3      │ 1184x864    │ 1290   │                               │
            # │ 4:5      │ 896x1152    │ 1290   │                               │
            # │ 5:4      │ 1152x896    │ 1290   │                               │
            # │ 9:16     │ 768x1344    │ 1290   │                               │
            # │ 16:9     │ 1344x768    │ 1290   │                               │
            # │ 21:9     │ 1536x672    │ 1290   │                               │
            # └──────────┴─────────────┴────────┘                               │
            # └─────────────────────────────────────────────────────────────────┘
            #
            # ┌─────────────────────────────────────────────────────────────────┐
            # │ Gemini 3 Pro Image 预览版                                        │
            # ├──────────┬─────────────────────────────────────────────────────┐│
            # │ 宽高比    │ 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                             │
            # └─────────────────────────────────────────────────────────────────┘
            "aspectRatio": "1:1",

            # imageSize: 设置输出图片的分辨率
            # - "1K": 1K 分辨率(默认值,所有模型均支持)
            # - "2K": 2K 分辨率(仅 Gemini 3 Pro Image 预览版支持)
            # - "4K": 4K 分辨率(仅 Gemini 3 Pro Image 预览版支持)
            # 注意: gemini-2.5-flash-image 仅支持 1K,如需 2K/4K 请使用 gemini-3-pro-image-preview
            # "imageSize": "1K"
        }
    },

    # tools: Google 搜索工具(可选)
    # - 使用实时信息生成图像(如根据最新资讯添加元素等)
    # - 注意: 使用搜索工具时必须设置 responseModalities: ['TEXT', 'IMAGE']
    # - 图片专用模式 ['IMAGE'] 与搜索工具不兼容
    # "tools": [{"google_search": {}}]
}

# 完整的 API 端点
API_URL = f"{BASE_URL}/models/{payload['model']}:generateContent"

# ========================================
# 发送 API 请求并处理响应
# ========================================
try:
    # 发送 POST 请求到 API 服务器
    response = requests.post(API_URL, headers=headers, json=payload, timeout=(30, 300))

    # 检查 HTTP 响应状态码
    response.raise_for_status()

    # ========================================
    # 输出成功结果
    # ========================================
    print("请求成功!")
    print("=" * 60)

    result = response.json()
    image_saved = False

    for candidate in result.get("candidates", []):
        for part in candidate.get("content", {}).get("parts", []):
            if "text" in part:
                print(f"文本响应: {part['text']}")
            elif "inlineData" in part:
                image_data = part["inlineData"].get("data", "")
                if image_data:
                    os.makedirs("output", exist_ok=True)
                    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
                    filename = f"output/gemini-edited-image_{timestamp}.png"

                    with open(filename, 'wb') as f:
                        f.write(base64.b64decode(image_data))

                    print(f"图片已保存到: {filename}")
                    image_saved = True

    if not image_saved:
        print("响应中没有找到图片数据")

except requests.exceptions.RequestException as e:
    print(f"请求失败: {e}")
except ValueError as e:
    print(f"数据解析错误: {e}")

运行结果

json
请求成功!
============================================================
图片已保存到: output/gemini-edited-image_20251208_222523.png

注意事项

  1. API 密钥:请将代码中的 api_key 替换为你自己的 DMXAPI 密钥
  2. 图片路径:确保 INPUT_IMAGE_PATH 指向的图片文件存在
  3. 分辨率限制
    • gemini-2.5-flash-image 仅支持 1K 分辨率
    • gemini-3-pro-image-preview 支持 1K/2K/4K 分辨率
  4. 搜索工具限制:使用 Google 搜索工具时必须设置 response_modalities=['Text', 'Image']

© 2025 DMXAPI - Gemini 图像编辑 API 文档

一个 Key 用全球大模型