> ## 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 リファレンス

> Tencent Hunyuan Hy-Image 3.5 Preview のテキストから画像への API リファレンスとプレイグラウンド — hy-image-v3.5-preview-2k / -4k、2048/4096 固定出力、デフォルトの b64_json、オプションの CDN URL

> [!NOTE]
>
> 右側のインタラクティブなPlaygroundでは、ライブテストを実行できます。**Authorization** にAPIキー（形式: `Bearer sk-xxx`）を入力し、`model`を選択して、`prompt`を入力します。必要に応じて`response_format`を選択し、送信します。**`size`には入力しないでください**。どちらのモデルも出力サイズが固定されています。

> [!TIP]
>
> **このページを使用する場面**: テキストから画像への生成のみを行う場合です。必要なのはpromptだけです。参照画像の生成または編集には、[参照画像 API](https://docs.apiyi.com/ja/api-capabilities/hunyuan-image/image-edit.md)を使用してください。

> [!WARNING]
>
> **⚠️ 知っておくべき3つのこと**
>
> * **`size`はモデルによって上書きされます**: `-2k`は常に2048×2048を返し、`-4k`は常に4096×4096を返します。`size`で解像度を切り替えようとしないでください。
> * **`n`は1に固定されています**: 2または3を渡しても、1枚の画像のみが返され、1回分のみ課金されます。複数の画像を取得するには、同時実行リクエストを送信してください。
> * **レスポンスはデフォルトでbase64です**: 2Kのレスポンスは約6～8.4 MB、4Kのレスポンスは17.6～20 MBです。Web上で表示する場合は、`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  # 120s for 2K; use 240s for 4K
)

resp = client.images.generate(
    model="hy-image-v3.5-preview-2k",
    prompt="A cinematic Chinese movie poster with the title \"Between Mountains and Seas\" centered, deep blue night sky and golden mountains, premium finish",
    # Do not pass size; responses default to b64_json
)

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

### Python（生のリクエスト）

```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": "An orange cat wearing sunglasses on a wooden windowsill, afternoon sunlight, cinematic shallow depth of field",
        "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": "A minimalist coffee shop poster with the headline \"Autumn Limited\" at the top, warm brown palette",
    "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)  // 240s for 4K
});

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

### ブラウザ JavaScript（URL モード）

```javascript theme={null}
{/* Demo only. Use a backend proxy in production to avoid leaking the 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: 'A cinematic poster with the title "Between Mountains and Seas", deep blue night sky and golden mountains',
        response_format: 'url'  // Return a CDN URL instead of a 6–26 MB base64 string
    })
});

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`。無効な値は警告なしで base64 にフォールバックします |
| ~~`size`~~ | — | — | — | **モデルによって上書きされます**。渡さないでください |
| ~~`n`~~ | — | — | — | **1 に固定されています**。その他の値でも画像は1枚返されます |
| `images` / `image` | — | — | — | テキストから画像への変換には不要です。[参照画像 API](https://docs.apiyi.com/ja/api-capabilities/hunyuan-image/image-edit.md) を使用してください |

> [!TIP]
>
> 制約と許可される値については、プレイグラウンドのフィールド説明を参照してください。`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`は\*\*`data:image/png;base64,`プレフィックスのないプレーンな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です。このシリーズでは画像1枚ごとに定額で課金されます。実際の課金額については、APIYIコンソールの請求情報を使用してください。


## OpenAPI

````yaml api-reference/hunyuan-image-generate-openapi-en.yaml POST /v1/images/generations
openapi: 3.1.0
info:
  title: Tencent Hunyuan Hy-Image 3.5 Preview Text-to-Image API
  description: >
    Tencent Cloud official-relay Hunyuan Hy-Image-3.5-preview image model —
    text-to-image endpoint.


    - Two public models: `hy-image-v3.5-preview-2k` (fixed 2048×2048,
    \$0.022/image) and `hy-image-v3.5-preview-4k` (fixed 4096×4096,
    \$0.030/image)

    - List prices match the official list; top-up bonuses bring the effective
    price to about **83–91% of list**. See [Top-up
    Bonuses](/en/faq/recharge-promotions)

    - Flat per-image pricing, regardless of `size`, `response_format`, or the
    number of reference images; exactly 1 image per request

    - Returns `data[0].b64_json` by default (plain base64, no `data:` prefix);
    pass `response_format: "url"` to receive a platform CDN URL

    - `size` is overridden by the model's fixed resolution; `n` is fixed at 1

    - Strong Chinese text rendering, suitable for posters, e-commerce hero
    images, and film assets


    **Authentication**: add `Authorization: Bearer YOUR_API_KEY` to the request
    headers.


    **Get an API key**: create a Token in the [APIYI
    console](https://api.apiyi.com/token)
  version: 1.0.0
servers:
  - url: https://api.apiyi.com
    description: Primary endpoint
security:
  - bearerAuth: []
paths:
  /v1/images/generations:
    post:
      tags:
        - Text-to-Image
      summary: 'Text-to-image: generate a 2K/4K image from a prompt'
      description: >
        Generate an image with `hy-image-v3.5-preview-2k` or
        `hy-image-v3.5-preview-4k`.


        - Required: `model`, `prompt`

        - Optional: `response_format` (`b64_json` by default, or `url`)

        - Do not pass `size`: `-2k` is fixed at 2048×2048 and `-4k` at 4096×4096

        - `n` is fixed at 1; send concurrent requests for multiple images

        - For reference-image generation, use the [reference-image
        endpoint](/en/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: >-
                A cinematic movie poster with the Chinese title "Between
                Mountains and Seas" centered, deep blue night sky and golden
                mountains, premium finish
              response_format: b64_json
      responses:
        '200':
          description: Image generated successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ImageResponse'
        '400':
          description: >-
            Invalid parameters: missing prompt returns `invalid_image_request`;
            content moderation returns `content_safety_violation`
        '401':
          description: Unauthorized - invalid API key
        '429':
          description: Rate limit exceeded or insufficient quota
        '500':
          description: Internal server error
        '503':
          description: Wrong model name, or no available channel in the current group
      security:
        - bearerAuth: []
components:
  schemas:
    HunyuanImageGenerateRequest:
      type: object
      required:
        - model
        - prompt
      properties:
        model:
          type: string
          description: Model ID. `-2k` is fixed at 2048×2048; `-4k` is fixed at 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: >-
            Prompt, Chinese or English. Wrap text that must appear in the image
            in quotes
          example: >-
            A cinematic movie poster with the Chinese title "Between Mountains
            and Seas" centered, deep blue night sky and golden mountains,
            premium finish
        response_format:
          type: string
          description: >-
            Response format. Defaults to `b64_json`; `url` returns a stable
            platform CDN URL
          enum:
            - b64_json
            - url
          default: b64_json
        'n':
          type: integer
          description: Fixed at 1. This model always returns exactly one image
          enum:
            - 1
          default: 1
    ImageResponse:
      type: object
      properties:
        created:
          type: integer
          description: Unix timestamp
          example: 1795534600
        id:
          type: string
          description: Task ID for this request
          example: tsk_01m8736tvsqp2t27p0k53hjn7z
        data:
          type: array
          description: Image result array, always exactly one item
          items:
            type: object
            properties:
              b64_json:
                type: string
                description: Plain base64 PNG data, no `data:` prefix (returned by default)
                example: iVBORw0KGgoAAAANSUhEUgAA...
              url:
                type: string
                description: Image URL (returned when response_format=url)
                example: https://hdcdn.agisuitepro.com/o/2026/11/24/example.png
        usage:
          type: object
          description: >
            **Placeholder values; do not use for billing reconciliation.**
            `prompt_tokens` is always 1000 and `output_tokens` is always 0.

            Actual charges are flat per image and come from the console bill.
          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 key created in the APIYI console

````

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