> ## 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 референсных изображений

> Справочник API референсных изображений Tencent Hunyuan Hy-Image 3.5 Preview и песочница — массив images остается фиксированным на уровне 2K/4K, устаревшее поле image по умолчанию использует 1536, а операции редактирования multipart выводят только 1536

> [!NOTE]
>
> Интерактивная Playground справа поддерживает тестирование в реальном времени. Поле `images` принимает **общедоступные URL изображений** или `data:image/...;base64,...`; загрузка локальных файлов не поддерживается. Преобразуйте локальные файлы в URI данных с помощью приведённых ниже примеров.

> [!TIP]
>
> **Когда использовать эту страницу**: для генерации изображения на основе одного или нескольких эталонных изображений — переноса стиля, сохранения композиции, объединения нескольких изображений или перерисовки с использованием эталона. Для обычной генерации изображений из текста используйте [API преобразования текста в изображение](https://docs.apiyi.com/ru/api-capabilities/hunyuan-image/text-to-image.md).

> [!WARNING]
>
> **⚠️ Три способа передачи эталонных изображений с разными размерами выходных данных**
>
> * **Массив `images` (рекомендуется)**: фиксированный размер 2048×2048 (`-2k`) или 4096×4096 (`-4k`); явно заданное значение `size` игнорируется.
> * **Устаревшее поле `image`**: выводит только изображение размером **1536×1536** без `size`; для 2K/4K явно передайте `size`, но тарификация остаётся фиксированной ценой модели.
> * **`/v1/images/edits` multipart**: работает, но выводит только изображение размером **1536×1536** и не использует переопределение 2K/4K. Не рекомендуется.
>
> **`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  # 120s for 2K; use 240s for 4K
)

resp = client.images.generate(
    model="hy-image-v3.5-preview-2k",
    prompt="Turn the reference image into a watercolor painting while keeping the red circle and blue square in place",
    extra_body={
        # Data URIs such as "data:image/png;base64,..." also work
        "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 (необработанные запросы с 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": "Turn the reference image into a watercolor painting while keeping the red circle and blue square in place",
        "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": "Turn the reference image into a watercolor painting while keeping the red circle and blue square in place",
    "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: 'Place the person from image 1 into the scene from image 2, keeping the clothing color from image 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` (явный размер для 2K/4K)

```python theme={null}
resp = client.images.generate(
    model="hy-image-v3.5-preview-2k",
    prompt="Turn the reference image into a watercolor painting while keeping the composition",
    extra_body={
        "image": ["https://docs.apiyi.com/images/hunyuan-image-v35-reference-input.png"],
        "size": "2048x2048"  # Legacy field: without size, output is only 1536×1536
    }
)
```

### Редактирование через multipart (не рекомендуется)

```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=Turn the reference image into a watercolor painting while keeping the composition" \
  -F "image=@reference.png"
```

> [!WARNING]
>
> При использовании multipart `/v1/images/edits` результаты имеют только размер **1536×1536**, и переопределение `size` для 2K/4K не применяется. Этот вариант существует для совместимости со старым кодом и не рекомендуется для новых проектов.

## Параметры

| Параметр | Тип | Обязательный | Значение по умолчанию | Описание |
| - | - | - | - | - |
| `model` | string | Да | — | `hy-image-v3.5-preview-2k` (2048×2048) или `hy-image-v3.5-preview-4k` (4096×4096) |
| `prompt` | string | Да | — | Инструкция по генерации/редактированию; укажите, что нужно сохранить, а что изменить |
| `images` | string\[] | Да (рекомендуется) | — | Референсные изображения в виде общедоступных URL или URI данных; результат остаётся фиксированным: 2K/4K |
| `image` | string / string\[] | Нет (устаревший параметр) | — | Путь редактирования; результаты доступны только в формате 1536×1536 без `size` |
| `size` | string | Нет | — | Применяется только к устаревшему полю `image`; для `images` переопределяется |
| `response_format` | string | Нет | `b64_json` | `b64_json` или `url` |
| ~~`n`~~ | — | — | — | **Фиксировано на уровне 1** |

> [!TIP]
>
> Количество референсов не влияет на цену. В официальной документации указано ограничение: не более 20 МБ на изображение и не более 20 входных изображений всего. При использовании нескольких референсов ссылайтесь на них в промпте как «изображение 1 / изображение 2».

## Подготовка референсов

* **Форматы**: PNG, JPEG или WebP; каждое изображение ≤20 МБ.
* **URL**: должны быть общедоступными прямыми ссылками. Ссылки, требующие авторизации, защищённые от хотлинкинга или подписанные URL с истёкшим сроком действия не позволяют скачать файл.
* **URI данных**: преобразуйте локальные файлы в `data:image/png;base64,...` и поместите их в массив `images`. Подходит для небольших файлов и частных сетей.
* **Сжатие**: уменьшите длинную сторону до 2048 пикселей и используйте качество 0.9; общий размер должен быть меньше примерно 6 МБ, чтобы сократить время передачи и обработки.
* **Порядок**: референсы нумеруются в порядке элементов массива `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 составляет около 3–7 МБ, а в 4K — около 18–19 МБ; размер ответа в base64 для 4K может достигать 26 МБ.

> [!NOTE]
>
> **`usage` не содержит данных для тарификации**: `prompt_tokens` всегда равно 1000, а `output_tokens` всегда равно 0. В этой серии применяется фиксированная цена за изображение; фактические начисления смотрите в счёте в консоли APIYI.

## Связанная документация

* [Справочник API генерации изображений по тексту](https://docs.apiyi.com/ru/api-capabilities/hunyuan-image/text-to-image.md)
* [Часто задаваемые вопросы о Hunyuan Hy-Image 3.5](https://docs.apiyi.com/ru/api-capabilities/hunyuan-image/faq.md)
* [Рекомендации по работе с API изображений](https://docs.apiyi.com/ru/api-capabilities/image-api-best-practices.md)


## OpenAPI

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


    - Recommended field `images`: a JSON array whose items are public image URLs
    or `data:image/...;base64,...`

    - The `images` path always outputs 2048×2048 (`-2k`) or 4096×4096 (`-4k`);
    an explicit `size` is overridden

    - Legacy field `image`: string or array, routed through the edit path;
    without `size` it outputs only 1536×1536. Pass `size` explicitly for 2K/4K,
    but billing is still the model's flat price

    - `/v1/images/edits` multipart also works, but outputs only 1536×1536 and is
    not recommended

    - Returns `data[0].b64_json` by default; pass `response_format: "url"` for a
    platform CDN URL

    - Exactly 1 image per request; `n` is fixed at 1


    **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:
        - Reference Image
      summary: >-
        Reference-image generation: create a 2K/4K image from references and a
        prompt
      description: >
        Generate an image with `hy-image-v3.5-preview-2k` or
        `hy-image-v3.5-preview-4k` from one or more reference images.


        - Required: `model`, `prompt`, `images` (at least one)

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

        - Legacy `image`: without `size` it outputs 1536×1536; pass `size`
        explicitly for 2K/4K

        - `/v1/images/edits` multipart outputs only 1536×1536 and is not
        recommended

        - Each reference image ≤20MB; the official docs list a total input limit
        of 20 images
      operationId: generateHunyuanImageFromReferences
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/HunyuanImageReferenceRequest'
            example:
              model: hy-image-v3.5-preview-2k
              prompt: >-
                Turn the reference image into a watercolor painting while
                keeping the red circle and blue square in place
              images:
                - >-
                  https://docs.apiyi.com/images/hunyuan-image-v35-reference-input.png
              response_format: b64_json
      responses:
        '200':
          description: Image generated successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ImageResponse'
        '400':
          description: >-
            Missing prompt, empty reference images (`invalid_image_request`), or
            content moderation (`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:
    HunyuanImageReferenceRequest:
      type: object
      required:
        - model
        - prompt
        - images
      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: Edit/generation instruction. State what to keep and what to change
          example: >-
            Turn the reference image into a watercolor painting while keeping
            the red circle and blue square in place
        images:
          type: array
          description: >
            Reference images. Items can be public URLs or
            `data:image/...;base64,...`.

            This is the recommended field; output is fixed at the model's 2K/4K
            resolution.
          minItems: 1
          maxItems: 20
          items:
            type: string
          example:
            - >-
              https://docs.apiyi.com/images/hunyuan-image-v35-reference-input.png
        image:
          type: string
          description: >
            Legacy field, not recommended. Routed through the edit path: outputs
            1536×1536 without `size`;

            pass `size` explicitly for 2K/4K. Billing is still the model's flat
            price.
          example: https://docs.apiyi.com/images/hunyuan-image-v35-reference-input.png
        size:
          type: string
          description: >
            Only applies to the legacy `image` field; ignored when using
            `images`.

            Common values: `2048x2048` (2K) or `4096x4096` (4K).
          example: 2048x2048
        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.