> ## 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/zh-Hant/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/zh-Hant/api-capabilities/hunyuan-image/text-to-image.md)
* [混元 Hy-Image 3.5 常見問題](https://docs.apiyi.com/zh-Hant/api-capabilities/hunyuan-image/faq.md)
* [圖片 API 呼叫須知與最佳實踐](https://docs.apiyi.com/zh-Hant/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.