> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hingnet.com.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# 图像生成 (OpenAI 风格)

> 使用 OpenAI 兼容接口调用 Gemini 图像生成模型

本文档介绍如何通过 OpenAI 风格的 `/v1/images/generations` 和 `/v1/images/edits` 接口调用 Gemini 图像生成模型。

## 异步模式（适用于 Gemini 图像模型 / Imagen 文生图）

针对 Gemini 图像模型与 Imagen 文生图，本网关提供 Sora 风格的异步任务接口：

* 创建文生图任务：`POST /v1/images/generations/async`
* 创建改图任务：`POST /v1/images/edits/async`
* 查询任务状态：`GET /v1/images/generations/{id}` / `GET /v1/images/edits/{id}`

<Note>
  异步模式强制要求配置对象存储（S3/OSS），用于上传生成图片并返回 24 小时有效的临时 URL。
  同时，异步模式下 `response_format` 固定为 `url`（即使传入 `b64_json` 也会忽略）。
  创建任务的响应中 `task_id` 为兼容字段，等同于 `id`。
  改图异步任务仅支持 Gemini 图像模型（`gemini-*-image*`），Imagen 暂不支持编辑。
  更多细节请参考《[图像生成（异步接口）](/gemini/images-async)》。
</Note>

### 只返回图像 URL（`response_format=url`）

在同步接口（`/v1/images/generations`、`/v1/images/edits`）中，将 `response_format` 设置为 `url` 可让返回体只包含图片 URL（`data[].url`），同时会清空 `data[].b64_json`。

<Note>
  * 若返回的数据本身已包含 URL：本网关会直接透传 URL，并清空 `b64_json`。
  * 若返回的是 `b64_json`：本网关会尝试将图片上传到已配置的 storage（如 S3/R2/OSS/图床等），再返回 URL；若未配置 storage，将返回错误（`error.code=image_url_not_available`）。
  * 异步接口（`/async`）同样是“只返回 URL”，并且强制要求对象存储（S3/OSS），返回的是 24 小时有效的临时签名 URL。
</Note>

同步文生图（URL-only）示例：

```bash theme={null}
curl -X POST "$BASE_URL/v1/images/generations" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-3-pro-image-preview",
    "prompt": "一只熊猫在图书馆看书，电影级光影",
    "n": 1,
    "size": "1K",
    "response_format": "url"
  }'
```

### 异步文生图示例

```bash theme={null}
# 1) 创建任务
curl -X POST "$BASE_URL/v1/images/generations/async" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-3-pro-image-preview",
    "prompt": "A futuristic cityscape at sunset with flying cars",
    "n": 1,
    "size": "1024x1024",
    "response_format": "url"
  }'

# 2) 轮询查询（将返回 data[0].url）
curl -X GET "$BASE_URL/v1/images/generations/{id}" \
  -H "Authorization: Bearer $TOKEN"
```

## 支持的模型

| 模型                                                          | 说明      | 最大分辨率          | 特点              |
| ----------------------------------------------------------- | ------- | -------------- | --------------- |
| `gemini-3-pro-image-preview`                                | 高质量图像生成 | 4K (4096×4096) | 支持复杂提示词理解、参考图编辑 |
| `gemini-2.5-flash-image` / `gemini-2.5-flash-image-preview` | 快速图像生成  | 1K (1024×1024) | 低延迟，适合原型验证      |

<Note>
  Imagen 系列（`imagen-*`）仅支持文生图（`/v1/images/generations`），不支持改图。
</Note>

***

## 文生图 `/v1/images/generations`

### 基础请求

```bash theme={null}
curl -X POST "$BASE_URL/v1/images/generations" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-3-pro-image-preview",
    "prompt": "一只熊猫在图书馆看书，电影级光影",
    "n": 1,
    "size": "1K",
    "aspect_ratio": "1:1",
    "response_format": "b64_json"
  }'
```

### 请求参数

| 参数                | 类型      | 必填 | 说明                               |
| ----------------- | ------- | -- | -------------------------------- |
| `model`           | string  | ✅  | 模型名称                             |
| `prompt`          | string  | ✅  | 图像描述文本                           |
| `n`               | integer | ❌  | 生成数量，默认 1（仅支持 1）                 |
| `size`            | string  | ❌  | 分辨率，见下方说明                        |
| `response_format` | string  | ❌  | `b64_json` 或 `url`，默认 `b64_json` |
| `aspect_ratio`    | string  | ❌  | 宽高比，如 `1:1`、`16:9`、`9:16`        |

### 分辨率与计费档位

`size` 参数支持两种格式：

1. **档位格式（推荐）**：`"1K"`、`"2K"`、`"4K"`
2. **数字格式**：如 `"1024x1024"`，用于兼容历史写法（仅作为推断档位和宽高比的“提示”，最终像素按栅格表决定）

系统会根据 `size` 以及 `aspect_ratio` 自动计算标准分辨率档位（1K / 2K / 4K），并映射到对应的分辨率配置：

| 档位 | 含义                 | 建议用途            |
| -- | ------------------ | --------------- |
| 1K | 约 1K 级别像素（最长边约 1K） | 预览、小图、移动端壁纸     |
| 2K | 约 2K 级别像素          | 高清插画、桌面壁纸       |
| 4K | 约 4K 级别像素          | 超高清、精修图、打印或大屏展示 |

各宽高比在不同档位下的具体像素栅格（例如 1K/2K/4K 下 16:9、9:16、2:3 等对应的精确分辨率），请参考《[Gemini 图像生成](/gemini/images)》文档中的 **“分辨率与宽高比”** 小节。

<Note>
  `gemini-2.5-flash-image` 最高仅支持 1K 分辨率。
</Note>

### 宽高比设置

两种方式控制图像比例：

```json theme={null}
// 方式 1：只通过 size（数字）推断
{"size": "1024x1024"}  // 自动推断为 1K + 1:1

// 方式 2：推荐写法——档位 + 显式指定 aspect_ratio（优先级更高）
{"size": "2K", "aspect_ratio": "16:9"}
```

当前支持的宽高比包括：

`1:1`、`2:3`、`3:2`、`3:4`、`4:3`、`4:5`、`5:4`、`9:16`、`16:9`、`21:9`

### 响应结构

```json theme={null}
{
  "created": 1700000000,
  "data": [
    {
      "b64_json": "<BASE64_IMAGE_DATA>",
      "revised_prompt": "优化后的提示词（如有）"
    }
  ]
}
```

当 `response_format=url` 时，响应将返回 `data[].url`，并且 `b64_json` 会为空：

```json theme={null}
{
  "created": 1700000000,
  "data": [
    {
      "url": "https://example.com/xxx.png"
    }
  ]
}
```

### Python SDK 示例

```python theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="https://models.hingnet.com.cn/v1",
    api_key="oh-xxxxxxxxxxxxxxxx",
)

resp = client.images.generate(
    model="gemini-3-pro-image-preview",
    prompt="赛博朋克风格的未来城市，霓虹灯倒映在雨水中",
    size="2048x2048",
    response_format="b64_json",
)

# 获取 base64 图片数据
image_b64 = resp.data[0].b64_json
```

***

## 参考图编辑 `/v1/images/edits`

通过上传参考图实现图像编辑、风格迁移等功能。

### 基础请求

```bash theme={null}
curl -X POST "$BASE_URL/v1/images/edits" \
  -H "Authorization: Bearer $TOKEN" \
  -F "model=gemini-3-pro-image-preview" \
  -F "prompt=将这张图片转换为油画风格" \
  -F "response_format=b64_json" \
  -F "image=@/path/to/image.png"
```

### 多参考图请求

```bash theme={null}
curl -X POST "$BASE_URL/v1/images/edits" \
  -H "Authorization: Bearer $TOKEN" \
  -F "model=gemini-3-pro-image-preview" \
  -F "prompt=保持第一张图的构图，参考第二张的色调" \
  -F "response_format=b64_json" \
  -F "size=2048x2048" \
  -F "image=@/path/base.png" \
  -F "image[]=@/path/ref1.png" \
  -F "image[]=@/path/ref2.png"
```

### 通过 URL 传入参考图

支持通过 `image_urls[]` 参数直接传入图片 URL，无需上传文件：

```bash theme={null}
curl -X POST "$BASE_URL/v1/images/edits" \
  -H "Authorization: Bearer $TOKEN" \
  -F "model=gemini-3-pro-image-preview" \
  -F "prompt=将这张图转换为水彩风格" \
  -F "response_format=b64_json" \
  -F "image_urls[]=https://example.com/base.png" \
  -F "image_urls[]=https://example.com/style-ref.png"
```

<Note>
  * `image_urls[]` 中的第一个 URL 作为基准图，其余作为参考图
  * 可与 `image`/`image[]` 混用，总计最多 14 张
  * 仅支持公网可访问的 HTTP/HTTPS 图片 URL
  * 不支持 localhost 和内网 IP 地址
</Note>

### 请求参数

| 参数                | 类型        | 必填 | 说明                                                   |
| ----------------- | --------- | -- | ---------------------------------------------------- |
| `model`           | string    | ✅  | 模型名称                                                 |
| `prompt`          | string    | ✅  | 编辑指令                                                 |
| `image`           | file      | ❌  | 基准图（主图），与 `image_urls[]` 二选一                         |
| `image[]`         | file\[]   | ❌  | 参考图，最多 14 张                                          |
| `image_urls[]`    | string\[] | ❌  | 图片 URL 列表，第一个作为基准图，其余作为参考图；与 `image`/`image[]` 可混用   |
| `size`            | string    | ❌  | 输出分辨率，默认自动从基准图推断（支持 `1K`、`2K`、`4K` 或 `widthxheight`） |
| `aspect_ratio`    | string    | ❌  | 显式指定宽高比，如 `1:1`、`16:9`、`9:16`                        |
| `response_format` | string    | ❌  | `b64_json` 或 `url`                                   |
| `mask`            | file      | ❌  | 蒙版图（局部编辑时使用）                                         |

### 自动分辨率推断

当未指定 `size` 时，系统会自动从基准图推断输出分辨率：

* 读取基准图（`image` 字段）的实际尺寸
* 按模型最大能力限制输出（如 `gemini-2.5-flash-image` 最大 1024）
* 保持原图宽高比

<Note>
  - 自动推断功能仅对 `gemini-3-pro-image-preview` 生效；
  - 当显式传入 `aspect_ratio` 时，会优先使用该宽高比，并结合 `size`（或基准图尺寸推断的档位）进行分辨率配置。
</Note>

***

## 计费说明

采用混合计费模式：

| 计费项  | 说明                                       |
| ---- | ---------------------------------------- |
| 文本输入 | 按提示词的 tokens 数量计费                        |
| 图像输出 | 1K/2K 档：1120 tokens/张；4K 档：2000 tokens/张 |

示例计算（Gemini 3 Pro Image 1K）：

```
输入：50 tokens × 输入价格
输出：1 张 × 1120 tokens × 输出价格
```

***

## 错误处理

| 错误码 | 说明   | 解决方案              |
| --- | ---- | ----------------- |
| 400 | 参数错误 | 检查 prompt、size 格式 |
| 413 | 图片过大 | 压缩参考图至 10MB 以内    |
| 429 | 超出限额 | 检查配额或等待重试         |

***

## 与原生 API 对比

如需使用 Gemini 原生协议（`generateContent`），请参阅 [Gemini 原生图像 API](/gemini/images-native)。

| 特性    | OpenAI 风格        | 原生 API |
| ----- | ---------------- | ------ |
| 学习成本  | 低（兼容 OpenAI SDK） | 中      |
| 功能完整度 | 覆盖常用场景           | 完整     |
