> ## 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/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/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.