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

# 参考图生图 API 参考

> 腾讯混元 Hy-Image 3.5 Preview 参考图生图 API 参考与在线调试 — images 数组固定 2K/4K，image 旧字段默认 1536，multipart edits 只出 1536

> [!NOTE]
>
> 右侧的交互式 Playground 支持直接调试。`images` 字段填**公网图片 URL** 或 `data:image/...;base64,...`，不支持在 Playground 里直接上传本地文件；本地图片请用下方代码示例转成 data URI。

> [!TIP]
>
> **场景说明**：本页用于「基于一张或多张参考图生成图片」——风格迁移、构图保留、多图融合、参考重绘。纯文本生成图片请使用 [文生图接口](https://docs.apiyi.com/api-capabilities/hunyuan-image/text-to-image.md)。

> [!WARNING]
>
> **⚠️ 三种参考图写法，输出尺寸不同**
>
> * **`images` 数组（推荐）**：固定输出 2048×2048（`-2k`）或 4096×4096（`-4k`），显式 `size` 也会被覆盖。
> * **`image` 旧字段**：不传 `size` 时只输出 **1536×1536**；显式传 `size` 才能出 2K/4K，但仍按型号固定价计费。
> * **`/v1/images/edits` multipart**：能出图，但只输出 **1536×1536**，不走 2K/4K 覆盖，不推荐作为主路径。
>
> **prompt 必填**：只传参考图、不传 prompt 会返回 400 `prompt is required`。

## 三种写法对比

| 写法 | 请求形态 | 默认输出 | 显式 `size` | 推荐度 |
| - | - | - | - | - |
| `images` 数组 | JSON，`POST /v1/images/generations` | **2048×2048 / 4096×4096** | 被型号固定值覆盖 | ✅ 推荐 |
| `image` 旧字段 | JSON，`POST /v1/images/generations` | **1536×1536** | 生效：2K/4K | ⚠️ 旧字段 |
| multipart | `POST /v1/images/edits`，`multipart/form-data` | **1536×1536** | 不生效 | ❌ 不推荐 |

> [!WARNING]
>
> **价格与输出尺寸无关**：三种写法都按所选型号固定价扣费。用 `image` 旧字段或 multipart 只拿到 1536×1536，但价格仍按 `-2k` / `-4k` 计算。对外集成请统一使用 `images`。

## 代码示例

### Python（OpenAI SDK + extra\_body）

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

client = OpenAI(
    api_key="sk-your-api-key",
    base_url="https://api.apiyi.com/v1",
    timeout=120.0  # 2K 建议 120s；4K 建议 240s
)

resp = client.images.generate(
    model="hy-image-v3.5-preview-2k",
    prompt="把参考图变成水彩画风格，保留红色圆形和蓝色方块的构图与位置",
    extra_body={
        # 也可以传 "data:image/png;base64,..."
        "images": [
            "https://docs.apiyi.com/images/hunyuan-image-v35-reference-input.png"
        ]
    }
)

with open("out.png", "wb") as f:
    f.write(base64.b64decode(resp.data[0].b64_json))
```

### Python（原生 requests · data URI）

```python theme={null}
import base64
import os
import requests

with open("reference.png", "rb") as f:
    data_uri = "data:image/png;base64," + base64.b64encode(f.read()).decode()

response = requests.post(
    "https://api.apiyi.com/v1/images/generations",
    headers={"Authorization": f"Bearer {os.environ['APIYI_API_KEY']}"},
    json={
        "model": "hy-image-v3.5-preview-2k",
        "prompt": "把参考图变成水彩画风格，保留红色圆形和蓝色方块的构图与位置",
        "images": [data_uri],
        "response_format": "b64_json",
    },
    timeout=120,
)
response.raise_for_status()

with open("out.png", "wb") as f:
    f.write(base64.b64decode(response.json()["data"][0]["b64_json"]))
```

### cURL（URL 参考图）

```bash theme={null}
curl -X POST "https://api.apiyi.com/v1/images/generations" \
  -H "Authorization: Bearer sk-your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "hy-image-v3.5-preview-4k",
    "prompt": "把参考图变成水彩画风格，保留红色圆形和蓝色方块的构图与位置",
    "images": ["https://docs.apiyi.com/images/hunyuan-image-v35-reference-input.png"],
    "response_format": "b64_json"
  }' | python3 -c "import sys,json,base64; open('out.png','wb').write(base64.b64decode(json.load(sys.stdin)['data'][0]['b64_json']))"
```

### Node.js（多张参考图）

```javascript theme={null}
import fs from 'node:fs';

const resp = await fetch('https://api.apiyi.com/v1/images/generations', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${process.env.APIYI_API_KEY}`
    },
    body: JSON.stringify({
        model: 'hy-image-v3.5-preview-2k',
        prompt: '把图1的人物放进图2的场景，保留图1的服装颜色',
        images: [
            'https://your-domain.com/person.png',
            'https://your-domain.com/scene.png'
        ],
        response_format: 'b64_json'
    }),
    signal: AbortSignal.timeout(120000)
});

const { data } = await resp.json();
fs.writeFileSync('out.png', Buffer.from(data[0].b64_json, 'base64'));
```

### `image` 旧字段（显式 size 才出 2K/4K）

```python theme={null}
resp = client.images.generate(
    model="hy-image-v3.5-preview-2k",
    prompt="把参考图变成水彩画风格，保留构图",
    extra_body={
        "image": ["https://docs.apiyi.com/images/hunyuan-image-v35-reference-input.png"],
        "size": "2048x2048"  # 旧字段必须显式传 size，否则只有 1536×1536
    }
)
```

### multipart edits（不推荐）

```bash theme={null}
curl -X POST "https://api.apiyi.com/v1/images/edits" \
  -H "Authorization: Bearer sk-your-api-key" \
  -F "model=hy-image-v3.5-preview-2k" \
  -F "prompt=把参考图变成水彩画风格，保留构图" \
  -F "image=@reference.png"
```

> [!WARNING]
>
> multipart `/v1/images/edits` 只输出 **1536×1536**，且不执行 2K/4K 的 `size` 覆盖；仅用于兼容旧代码，不建议新项目使用。

## 参数说明速查

| 参数 | 类型 | 必填 | 默认 | 说明 |
| - | - | - | - | - |
| `model` | string | 是 | — | `hy-image-v3.5-preview-2k`（2048×2048）或 `hy-image-v3.5-preview-4k`（4096×4096） |
| `prompt` | string | 是 | — | 参考图生成 / 编辑指令；说明要保留什么、改什么 |
| `images` | string\[] | 是（推荐） | — | 参考图数组，元素为公网 URL 或 data URI；固定输出 2K/4K |
| `image` | string / string\[] | 否（旧字段） | — | 走编辑路径；不传 `size` 只出 1536×1536 |
| `size` | string | 否 | — | 仅对 `image` 旧字段生效；`images` 路径会被覆盖 |
| `response_format` | string | 否 | `b64_json` | `b64_json` 或 `url` |
| ~~`n`~~ | — | — | — | **固定为 1** |

> [!TIP]
>
> 参考图数量不影响价格；官方文档标注单图 ≤20MB、输入图片总数 ≤20 张。多图时在 prompt 中用「图1 / 图2」明确指代顺序。

## 参考图准备

* **格式**：PNG / JPEG / WebP 均可；单图 ≤20MB。
* **URL**：必须是可公网访问的直链；带登录态、防盗链或已过期的签名 URL 会下载失败。
* **data URI**：本地文件转成 `data:image/png;base64,...` 后放进 `images` 数组；适合小图和内网环境。
* **压缩**：上传前按长边 2048px、质量 0.9 压缩；多图合计建议 ≤6MB，既省传输也降低原厂处理时间。
* **顺序**：多图按 `images` 数组顺序视为图1、图2……，prompt 里显式指代。

## 响应格式

```json theme={null}
{
  "created": 1795534600,
  "id": "tsk_01m8736tvsqp2t27p0k53hjn7z",
  "data": [
    {
      "b64_json": "iVBORw0KGgoAAAANSUhEUgAABAAAAAQACAIAAADwf7zU..."
    }
  ],
  "usage": {
    "prompt_tokens": 1000,
    "total_tokens": 1000,
    "input_tokens": 1000,
    "output_tokens": 0
  }
}
```

> [!WARNING]
>
> **响应字段说明**
>
> * `b64_json` 是**纯 base64，不带 `data:` 前缀**，解码后为 PNG。
> * `response_format: "url"` 时返回 `data[0].url`，域名为 `hdcdn.agisuitepro.com`。
> * `usage` 是占位值，不能用于核账。
> * 2K 参考图生的 PNG 约 3–7 MB，4K 约 18–19 MB；4K base64 响应可达 26 MB。

> [!NOTE]
>
> **`usage` 不能用来核账**：`prompt_tokens` 恒为 1000、`output_tokens` 恒为 0。本系列按张固定计费，真实扣费请以 API易 控制台的账单记录为准。

## 相关文档

* [文生图 API 参考](https://docs.apiyi.com/api-capabilities/hunyuan-image/text-to-image.md)
* [混元 Hy-Image 3.5 常见问题](https://docs.apiyi.com/api-capabilities/hunyuan-image/faq.md)
* [图片 API 调用须知与最佳实践](https://docs.apiyi.com/api-capabilities/image-api-best-practices.md)


## OpenAPI

````yaml api-reference/hunyuan-image-edit-openapi.yaml POST /v1/images/generations
openapi: 3.1.0
info:
  title: 腾讯混元 Hy-Image 3.5 Preview 参考图生图 API
  description: >
    腾讯云官转混元 Hy-Image-3.5-preview 图像模型 — 参考图生图接口。


    - 推荐字段 `images`：JSON 数组，元素可以是公网图片 URL 或 `data:image/...;base64,...`

    - `images` 路径固定输出 2048×2048（`-2k`）或 4096×4096（`-4k`），显式传 `size` 也会被覆盖

    - 旧字段 `image`：字符串或数组，走编辑路径；不传 `size` 时只输出 1536×1536，需要 2K/4K 必须显式传
    `size`，但仍按型号固定价计费

    - `/v1/images/edits` multipart 也可用，但只输出 1536×1536，不推荐作为主路径

    - 默认返回 `data[0].b64_json`；显式传 `response_format: "url"` 返回平台 CDN URL

    - 每次固定 1 张；`n` 固定为 1


    **认证方式**：在请求头中添加 `Authorization: Bearer YOUR_API_KEY`


    **获取 API Key**：访问 [API易控制台](https://api.apiyi.com/token) 创建令牌
  version: 1.0.0
servers:
  - url: https://api.apiyi.com
    description: 主要端点
security:
  - bearerAuth: []
paths:
  /v1/images/generations:
    post:
      tags:
        - 参考图生图
      summary: 参考图生图：根据参考图和提示词生成 2K/4K 图片
      description: >
        使用 `hy-image-v3.5-preview-2k` 或
        `hy-image-v3.5-preview-4k`，基于一张或多张参考图生成图片。


        - 必填：`model`、`prompt`、`images`（至少一张）

        - 推荐：`images: ["https://...", "data:image/png;base64,..."]`

        - 旧字段 `image`：不传 `size` 时输出 1536×1536；显式传 `size` 才输出 2K/4K

        - `/v1/images/edits` multipart 只输出 1536×1536，不推荐

        - 参考图单图 ≤20MB；官方文档标注输入图片总数 ≤20 张
      operationId: generateHunyuanImageFromReferences
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/HunyuanImageReferenceRequest'
            example:
              model: hy-image-v3.5-preview-2k
              prompt: 把参考图变成水彩画风格，保留红色圆形和蓝色方块的构图与位置
              images:
                - >-
                  https://docs.apiyi.com/images/hunyuan-image-v35-reference-input.png
              response_format: b64_json
      responses:
        '200':
          description: 成功生成图片
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ImageResponse'
        '400':
          description: >-
            缺少
            prompt、参考图为空（`invalid_image_request`），或内容审核拦截（`content_safety_violation`）
        '401':
          description: 未授权 - API Key 无效
        '429':
          description: 请求频率超限或额度不足
        '500':
          description: 服务器内部错误
        '503':
          description: 模型名写错，或当前分组无可用渠道
      security:
        - bearerAuth: []
components:
  schemas:
    HunyuanImageReferenceRequest:
      type: object
      required:
        - model
        - prompt
        - images
      properties:
        model:
          type: string
          description: 模型 ID。`-2k` 固定 2048×2048，`-4k` 固定 4096×4096
          enum:
            - hy-image-v3.5-preview-2k
            - hy-image-v3.5-preview-4k
          default: hy-image-v3.5-preview-2k
        prompt:
          type: string
          description: 编辑 / 生成指令，说明要保留什么、改什么
          example: 把参考图变成水彩画风格，保留红色圆形和蓝色方块的构图与位置
        images:
          type: array
          description: |
            参考图数组。元素可以是公网 URL 或 `data:image/...;base64,...`。
            推荐使用此字段；输出固定为型号对应的 2K/4K。
          minItems: 1
          maxItems: 20
          items:
            type: string
          example:
            - >-
              https://docs.apiyi.com/images/hunyuan-image-v35-reference-input.png
        image:
          type: string
          description: |
            旧字段，不推荐。走编辑路径：不传 `size` 时输出 1536×1536，
            显式传 `size` 才能输出 2K/4K；仍按型号固定价计费。
          example: https://docs.apiyi.com/images/hunyuan-image-v35-reference-input.png
        size:
          type: string
          description: |
            仅对旧字段 `image` 生效；使用 `images` 时会被型号固定值覆盖。
            旧字段常用值：`2048x2048`（2K）或 `4096x4096`（4K）。
          example: 2048x2048
        response_format:
          type: string
          description: 返回格式。默认 `b64_json`；传 `url` 返回平台 CDN 的稳定 URL
          enum:
            - b64_json
            - url
          default: b64_json
        'n':
          type: integer
          description: 固定为 1。本模型每次只返回 1 张，`n` 传其它值也不会多出图
          enum:
            - 1
          default: 1
    ImageResponse:
      type: object
      properties:
        created:
          type: integer
          description: Unix 时间戳
          example: 1795534600
        id:
          type: string
          description: 本次请求的任务 ID
          example: tsk_01m8736tvsqp2t27p0k53hjn7z
        data:
          type: array
          description: 图片结果数组，固定 1 项
          items:
            type: object
            properties:
              b64_json:
                type: string
                description: 纯 base64 PNG 数据，不带 `data:` 前缀（默认返回）
                example: iVBORw0KGgoAAAANSUhEUgAA...
              url:
                type: string
                description: 图片 URL（response_format=url 时返回）
                example: https://hdcdn.agisuitepro.com/o/2026/11/24/example.png
        usage:
          type: object
          description: |
            **占位值，不能用于核账。** `prompt_tokens` 恒为 1000、`output_tokens` 恒为 0；
            真实扣费按模型固定价、以控制台账单为准。
          properties:
            prompt_tokens:
              type: integer
              example: 1000
            total_tokens:
              type: integer
              example: 1000
            input_tokens:
              type: integer
              example: 1000
            output_tokens:
              type: integer
              example: 0
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: 在 API易控制台获取的 API Key

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.