Skip to content

图像 API

ModelGate 提供强大的 AI 图像生成 API,支持多种主流图像生成模型。通过简单的文本描述,即可生成高质量的图像。

API 概览

ModelGate 图像 API 提供统一的接口访问多种图像生成模型。

  • 统一接口: 一个 API 端点访问所有图像生成模型
  • 多模型支持: 支持豆包 Seedream、Google Nano Banana 等主流模型
  • 灵活配置: 支持自定义尺寸、输出格式等参数

API 端点

POST https://mg.aid.pub/api/v1/images/generations

注意

如果您使用 modelgate 网页端,Host 为: https://mg.aid.pub
如果您使用 modelgate 客户端,Host 为: http://localhost:13148

请求参数

参数名类型必填默认值说明
modelstring-模型名称,如 volcengine/doubao-seedream-4-0, google/nano-banana, google/nano-banana-pro
promptstring-图像描述文本
sizestring1024x1024图像尺寸,格式为 宽x高,如 1024x1024, 2048x2048。支持的尺寸取决于模型
number_resultsinteger1生成图像数量。volcengine/doubao-seedream-4-0 支持最多 15 张。google/nano-bananagoogle/nano-banana-pro只支持 1 张。
output_formatstringpng输出图像格式: png, jpeg。只有google/nano-bananagoogle/nano-banana-pro 支持该字段
output_typestringbase64输出类型: url (返回图像 URL), base64 (返回 base64 编码)
seed_imagesstring[]-种子图像数组,支持单图或多图输入。volcengine/doubao-seedream-4-0 支持多图,支持 Base64 和 URL 格式。google/nano-banana支持单图输入,支持 URL 格式。google/nano-banana-pro支持多图输入,支持 URL 格式。最大输入数量参考下方:支持的模型和参数

参数顺序说明

豆包模型 (volcengine/doubao-seedream-4-0) 参数顺序:

json
{
  "output_type": "base64",
  "number_results": 3,
  "model": "volcengine/doubao-seedream-4-0",
  "prompt": "描述文本",
  "size": "2560x1440",
  "output_format": "png"
}

Google 模型 (google/nano-banana 系列) 参数顺序:

json
{
  "model": "google/nano-banana",
  "prompt": "描述文本",
  "size": "1024x1024",
  "output_type": "base64",
  "output_format": "png"
}

基本调用示例

python
import requests
import json
import base64

url = "https://mg.aid.pub/api/v1/images/generations"

headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer your-modelgate-key"
}

# 豆包模型示例
payload = {
    "output_type": "base64",
    "number_results": 3,
    "model": "volcengine/doubao-seedream-4-0",
    "prompt": "A cat wearing a spacesuit",
    "size": "2560x1440",
    "output_format": "png"
}

response = requests.post(url, headers=headers, json=payload)
data = response.json()

# 处理返回的 base64 图像
for i, item in enumerate(data["data"]):
    base64_image = item["b64_json"]
    image_data = base64.b64decode(base64_image)
    with open(f"image_{i}.png", "wb") as f:
        f.write(image_data)
    print(f"图像 {i} 已保存到 image_{i}.png")
typescript
interface ImageGenerationRequest {
  model: string;
  prompt: string;
  size?: string;
  output_format?: string;
  output_type?: string;
  number_results?: number;
}

interface ImageGenerationResponse {
  created: number;
  data: Array<{
    url?: string;
    b64_json?: string;
  }>;
}

const url = 'https://mg.aid.pub/api/v1/images/generations';

// Google 模型示例
const payload: ImageGenerationRequest = {
  model: 'google/nano-banana',
  prompt: 'A cat wearing a spacesuit',
  size: '1024x1024',
  output_type: 'base64',
  output_format: 'png'
};

const response = await fetch(url, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer your-modelgate-key'
  },
  body: JSON.stringify(payload)
});

const data: ImageGenerationResponse = await response.json();
const base64Image = data.data[0]?.b64_json;
console.log('Base64 图像:', base64Image);
javascript
const url = 'https://mg.aid.pub/api/v1/images/generations';

// Google 模型示例
const payload = {
  model: 'google/nano-banana',
  prompt: 'A cat wearing a spacesuit',
  size: '1024x1024',
  output_type: 'base64',
  output_format: 'png'
};

const response = await fetch(url, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer your-modelgate-key'
  },
  body: JSON.stringify(payload)
});

const data = await response.json();
const base64Image = data.data[0]?.b64_json;
console.log('Base64 图像:', base64Image);
go
package main

import (
    "bytes"
    "encoding/base64"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "os"
)

type ImageRequest struct {
    Model         string `json:"model"`
    Prompt        string `json:"prompt"`
    Size          string `json:"size,omitempty"`
    OutputFormat  string `json:"output_format,omitempty"`
    OutputType    string `json:"output_type,omitempty"`
    NumberResults int    `json:"number_results,omitempty"`
}

type ImageResponse struct {
    Created int64 `json:"created"`
    Data    []struct {
        URL     string `json:"url,omitempty"`
        B64JSON string `json:"b64_json,omitempty"`
    } `json:"data"`
}

func main() {
    url := "https://mg.aid.pub/api/v1/images/generations"

    // 豆包模型示例
    payload := ImageRequest{
        OutputType:    "base64",
        NumberResults: 3,
        Model:         "volcengine/doubao-seedream-4-0",
        Prompt:        "A cat wearing a spacesuit",
        Size:          "2560x1440",
        OutputFormat:  "png",
    }

    jsonData, _ := json.Marshal(payload)

    req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("Authorization", "Bearer your-modelgate-key")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    body, _ := io.ReadAll(resp.Body)
    var result ImageResponse
    json.Unmarshal(body, &result)

    // 保存所有生成的图像
    for i, item := range result.Data {
        imageData, _ := base64.StdEncoding.DecodeString(item.B64JSON)
        filename := fmt.Sprintf("image_%d.png", i)
        os.WriteFile(filename, imageData, 0644)
        fmt.Printf("图像已保存到 %s\n", filename)
    }
}
bash
# 豆包模型示例
curl --location 'https://mg.aid.pub/api/v1/images/generations' \
  --header 'Content-Type: application/json' \
  --header 'Authorization: Bearer your-modelgate-key' \
  --data '{
    "output_type": "base64",
    "number_results": 3,
    "model": "volcengine/doubao-seedream-4-0",
    "prompt": "A cat wearing a spacesuit",
    "size": "2560x1440",
    "output_format": "png"
  }'

# Google 模型示例
curl --location 'https://mg.aid.pub/api/v1/images/generations' \
  --header 'Content-Type: application/json' \
  --header 'Authorization: Bearer your-modelgate-key' \
  --data '{
    "model": "google/nano-banana",
    "prompt": "A cat wearing a spacesuit",
    "size": "1024x1024",
    "output_type": "base64",
    "output_format": "png"
  }'

响应格式

URL 格式响应:

json
{
	"task_id": "03fb35089a8543f6a7eb4c27ecb0ebe3",
	"status": "completed",
	"model": "google/nano-banana-pro",
	"created": 1765174766,
	"data": [
		{
			"url": "https://cdn.modelgate.com/images/abc123.png"
		}
	],
	"usage": [
		{
			"quality": "default",
			"size": "1696x2528"
		}
	],
	"request_id": "1765174674381275"
}

Base64 格式响应:

json
{
	"task_id": "03fb35089a8543f6a7eb4c27ecb0ebe3",
	"status": "completed",
	"model": "google/nano-banana-pro",
	"created": 1765174766,
	"data": [
		{
			"content": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABAAAAAQACAIAAADwf7zUAAAAiXpUWHRSYXcgcHJvZm....."
		}
	],
	"usage": [
		{
			"quality": "default",
			"size": "1696x2528"
		}
	],
	"request_id": "1765174674381275"
}

支持的模型和参数

volcengine/doubao-seedream-4-0

ByteDance 的 Seedream v4.0 是一款先进的图像生成模型,支持文本到图像、图像到图像以及多图像工作流。

能力:

  • 输入模态: Text, Image
  • 输出模态: Image

支持的尺寸 (size 参数):

宽高比宽高像素值
1:12048x2048
4:32304x1728
3:41728x2304
16:92560x1440
9:161440x2560
3:22496x1664
2:31664x2496
21:93024x1296

参数限制:

  • 最大生成图像数: 15
  • 最大输入图像数: 10
  • 输出格式: URL, Base64

google/nano-banana

Google 的 Gemini 2.5 Flash Image (Nano Banana) 是一款具有上下文理解能力的图像生成模型。

能力:

  • 输入模态: Text, Image
  • 输出模态: Image
  • 分辨率: 1K

支持的尺寸 (size 参数):

  • 1024x1024
  • 832x1248 / 1248x832
  • 864x1184 / 1184x864
  • 896x1152 / 1152x896
  • 768x1344 / 1344x768
  • 1536x672

参数限制:

  • 最大输入图像数: 10
  • 输出格式: Base64, URL
  • 图像格式: JPEG, PNG
  • 水印: SynthID (隐形嵌入式水印)

google/nano-banana-pro

Google 最先进的图像生成和编辑模型,基于 Gemini 3 Pro 构建。

能力:

  • 输入模态: Text, Image
  • 输出模态: Image, Text
  • 分辨率: 1K-4K

支持的尺寸 (size 参数)-单图输入:

1K 分辨率:

  • 1024x1024
  • 768x1376 / 1376x768
  • 1584x672
  • 1152x928 / 928x1152
  • 848x1264 / 1264x848
  • 896x1200 / 1200x896

2K 分辨率:

  • 2048x2048
  • 1536x2752 / 2752x1536
  • 3168x1344
  • 2304x1856 / 1856x2304
  • 1696x2528 / 2528x1696
  • 1792x2400 / 2400x1792

4K 分辨率:

  • 4096x4096
  • 3072x5504 / 5504x3072
  • 6336x2688
  • 4608x3712 / 3712x4608
  • 3392x5056 / 5056x3392
  • 3584x4800 / 4800x3584

支持的尺寸 (size 参数)-多图输入:

1K 分辨率:

  • 848x1264 / 1264x848
  • 896x1200 / 1200x896

2K 分辨率:

  • 1696x2528 / 2528x1696
  • 1792x2400 / 2400x1792

4K 分辨率:

  • 3392x5056 / 5056x3392
  • 3584x4800 / 4800x3584

参数限制:

  • 最大输入图像数: 10
  • 输出格式: Base64, URL
  • 图像格式: JPEG, PNG
  • 水印: SynthID (隐形嵌入式水印)

错误处理

错误响应示例:

json
{
	"status": "error",   // completed:成功 、failed:失败、error:错误
	"message": {
		"task_id": "",
		"status": "failed",
		"created": 1765175242,
		"error": {
			"code": "",
			"message": "failed to validate request: invalid Size for nano-banana-pro model: 1024x10214. Must be a valid NxN format from supported resolutions"
		},
		"request_id": "1765175242023429"
	}
}

错误处理示例:

typescript
async function generateImage(payload: ImageGenerationRequest) {
  try {
    const response = await fetch('https://mg.aid.pub/api/v1/images/generations', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer your-modelgate-key'
      },
      body: JSON.stringify(payload)
    });

    const data = await response.json();

    // 检查是否有错误
    if (data.status === 'error') {
      const errorMessage = data.message?.error?.message || '未知错误';

      switch (data.code) {
        case 400:
          console.error('请求参数错误:', errorMessage);
          break;
        case 401:
          console.error('API Key 无效');
          break;
        case 402:
          console.error('余额不足,请充值');
          break;
        case 429:
          console.error('请求过于频繁,请稍后重试');
          // 实现指数退避重试
          if (data.is_retry) {
            await new Promise(resolve => setTimeout(resolve, 5000));
            return generateImage(payload);
          }
          break;
        case 500:
        case 503:
        case 508:
          console.error('服务器错误,请稍后重试:', errorMessage);
          break;
        default:
          console.error('未知错误:', errorMessage);
      }

      throw new Error(errorMessage);
    }

    return data;
  } catch (error) {
    console.error('请求失败:', error);
    throw error;
  }
}

最佳实践

  1. 选择合适的模型: 根据需要的分辨率和功能选择模型

    • 1K 图像: google/nano-banana
    • 高分辨率 (2K-4K): volcengine/doubao-seedream-4-0google/nano-banana-pro
  2. 批量生成: 使用 number_results 参数(仅豆包模型支持)一次生成多张图像比多次调用更高效

  3. 错误重试: 实现指数退避重试机制,特别是对于 429 和 5xx 错误

  4. 合理选择输出格式:

    • URL 格式: 适合大多数场景,节省带宽
    • Base64 格式: 适合需要立即处理图像数据的场景
  5. 内容审核: 对用户提供的提示词进行内容审核,避免生成违规内容

ModelGate 产品文档