> ## 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 參考與線上除錯 — hy-image-v3.5-preview-2k / -4k 固定 2048/4096，預設 b64_json，可選 CDN URL

> [!NOTE]
>
> 右側的互動式 Playground 支援直接線上除錯。請在 **Authorization** 中填入你的 API Key（格式：`Bearer sk-xxx`），選擇 `model`、輸入 `prompt`，按需選擇 `response_format` 後一鍵傳送即可。**不要填 `size`**，兩個型號的輸出尺寸都是固定的。

> [!TIP]
>
> **場景說明**：本頁用於「純文本生成圖片」。只需提示詞，無需上傳任何圖片。如需基於參考圖生成或編輯，請使用 [參考圖生圖介面](https://docs.apiyi.com/zh-Hant/api-capabilities/hunyuan-image/image-edit.md)。

> [!WARNING]
>
> **⚠️ 三個必須知道的點**
>
> * **`size` 會被型號固定值覆蓋**：`-2k` 恆出 2048×2048，`-4k` 恆出 4096×4096。不要試圖用 `size` 切換解析度。
> * **`n` 固定為 1**：傳 2、3 也只回 1 張，只扣 1 次費用；需要多張請併發請求。
> * **預設返回 b64**：2K 響應約 6–8.4 MB，4K 約 17.6–20 MB。網頁展示建議傳 `response_format: "url"`。

## 程式碼示例

### Python（OpenAI SDK 直連）

```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="中文電影海報，主標題「山海之間」四個大字居中，副標題「2026年11月24日 北京首映」，深藍夜色與金色山巒，高階質感",
    # 不要傳 size；預設返回 b64_json
)

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

### Python（原生 requests）

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

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": "一隻戴墨鏡的橘貓坐在木質窗臺上，午後陽光，電影感淺景深，高畫質攝影",
        "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

```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-2k",
    "prompt": "一張極簡風格的中文咖啡店海報，頂部大字寫著「秋日限定」，暖棕配色",
    "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（原生 fetch）

```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-4k',
        prompt: 'A serene Japanese garden with cherry blossoms, koi pond, golden hour',
        response_format: 'b64_json'
    }),
    signal: AbortSignal.timeout(240000)  // 4K 建議 240s
});

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

### 瀏覽器 JavaScript（URL 模式）

```javascript theme={null}
{/* 僅作演示，生產請走後端代理避免 Key 洩露 */}
const resp = await fetch('https://api.apiyi.com/v1/images/generations', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer sk-your-api-key'
    },
    body: JSON.stringify({
        model: 'hy-image-v3.5-preview-2k',
        prompt: '一張中文電影海報，主標題「山海之間」，深藍夜色與金色山巒',
        response_format: 'url'  // 讓瀏覽器直接拿 CDN URL，避免 6–26 MB base64
    })
});

const { data } = await resp.json();
document.getElementById('img').src = data[0].url;
```

## 引數說明速查

| 引數 | 型別 | 必填 | 預設 | 說明 |
| - | - | - | - | - |
| `model` | string | 是 | — | `hy-image-v3.5-preview-2k`（2048×2048）或 `hy-image-v3.5-preview-4k`（4096×4096） |
| `prompt` | string | 是 | — | 提示詞，支援中英文；要出現在圖裡的文字用引號括起來 |
| `response_format` | string | 否 | `b64_json` | `b64_json` 或 `url`；非法值會靜默按 b64 返回 |
| ~~`size`~~ | — | — | — | **會被型號固定值覆蓋**，不要傳 |
| ~~`n`~~ | — | — | — | **固定為 1**，傳其它值也只出 1 張 |
| `images` / `image` | — | — | — | 文生圖不需要；參考圖請用 [參考圖生圖介面](https://docs.apiyi.com/zh-Hant/api-capabilities/hunyuan-image/image-edit.md) |

> [!TIP]
>
> 詳細的引數約束、可選值、示例請檢視右側 Playground 中的欄位說明。`quality`、`style`、`output_format` 不生效，不要傳。

## 響應格式

預設 `response_format: "b64_json"`：

```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
  }
}
```

顯式 `response_format: "url"`：

```json theme={null}
{
  "created": 1795534600,
  "id": "tsk_01m8736tvsqp2t27p0k53hjn7z",
  "data": [
    {
      "url": "https://hdcdn.agisuitepro.com/o/2026/11/24/example.png"
    }
  ],
  "usage": {
    "prompt_tokens": 1000,
    "total_tokens": 1000,
    "input_tokens": 1000,
    "output_tokens": 0
  }
}
```

> [!WARNING]
>
> **響應欄位說明**
>
> * `b64_json` 是**純 base64，不帶 `data:image/png;base64,` 字首**，可直接解碼，解碼後為 PNG。
> * 2K 的 PNG 約 4.4–5.7 MB，base64 後響應體約 6–8.4 MB；4K 的 PNG 約 12.6–18.9 MB，base64 後約 17.6–20 MB。
> * `url` 模式返回 `hdcdn.agisuitepro.com` 的穩定 URL；HEAD 200，可直接 `<img>` 展示，但 CORS 預檢 403，前端 `fetch` / canvas 跨域取圖需要服務端代理。
> * `usage` 是佔位值，不能用來核對賬單。

> [!NOTE]
>
> **`usage` 不能用來核賬**：`prompt_tokens` 恆為 1000、`output_tokens` 恆為 0。本系列按張固定計費，真實扣費請以 API易 控制台的賬單記錄為準。


## OpenAPI

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


    - 两个公开型号：`hy-image-v3.5-preview-2k`（固定
    2048×2048，\$0.022/张）、`hy-image-v3.5-preview-4k`（固定 4096×4096，\$0.030/张）

    - 标价与官网一致；充值加赠后实际到手价约 **83–91 折**，详见 [充值活动说明](/faq/recharge-promotions)

    - 按张固定计费，不区分 `size`、`response_format` 与参考图数量；每次固定 1 张

    - 默认返回 `data[0].b64_json`（纯 base64，无 `data:` 前缀）；显式传 `response_format:
    "url"` 返回平台 CDN URL

    - `size` 参数会被型号固定值覆盖，不需要传；`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`
        - 可选：`response_format`（`b64_json` 默认 / `url`）
        - `size` 不需要传：`-2k` 固定 2048×2048，`-4k` 固定 4096×4096
        - `n` 固定为 1；需要多张请并发发起多次请求
        - 参考图生图请使用 [参考图生图接口](/api-capabilities/hunyuan-image/image-edit)
      operationId: generateHunyuanImageTextToImage
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/HunyuanImageGenerateRequest'
            example:
              model: hy-image-v3.5-preview-2k
              prompt: 中文电影海报，主标题「山海之间」四个大字居中，深蓝夜色与金色山峦，高级质感
              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:
    HunyuanImageGenerateRequest:
      type: object
      required:
        - model
        - prompt
      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: 中文电影海报，主标题「山海之间」四个大字居中，深蓝夜色与金色山峦，高级质感
        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.