Text-to-image: generate a 2K/4K image from a prompt
curl --request POST \
--url https://api.apiyi.com/v1/images/generations \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data '
{
"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"
}
'import requests
url = "https://api.apiyi.com/v1/images/generations"
payload = {
"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"
}
headers = {
"Authorization": "Bearer <token>",
"Content-Type": "application/json"
}
response = requests.post(url, json=payload, headers=headers)
print(response.text)const options = {
method: 'POST',
headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
body: JSON.stringify({
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'
})
};
fetch('https://api.apiyi.com/v1/images/generations', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.apiyi.com/v1/images/generations",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode([
'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'
]),
CURLOPT_HTTPHEADER => [
"Authorization: Bearer <token>",
"Content-Type: application/json"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"strings"
"net/http"
"io"
)
func main() {
url := "https://api.apiyi.com/v1/images/generations"
payload := strings.NewReader("{\n \"model\": \"hy-image-v3.5-preview-2k\",\n \"prompt\": \"A cinematic movie poster with the Chinese title \\\"Between Mountains and Seas\\\" centered, deep blue night sky and golden mountains, premium finish\"\n}")
req, _ := http.NewRequest("POST", url, payload)
req.Header.Add("Authorization", "Bearer <token>")
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.post("https://api.apiyi.com/v1/images/generations")
.header("Authorization", "Bearer <token>")
.header("Content-Type", "application/json")
.body("{\n \"model\": \"hy-image-v3.5-preview-2k\",\n \"prompt\": \"A cinematic movie poster with the Chinese title \\\"Between Mountains and Seas\\\" centered, deep blue night sky and golden mountains, premium finish\"\n}")
.asString();require 'uri'
require 'net/http'
url = URI("https://api.apiyi.com/v1/images/generations")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n \"model\": \"hy-image-v3.5-preview-2k\",\n \"prompt\": \"A cinematic movie poster with the Chinese title \\\"Between Mountains and Seas\\\" centered, deep blue night sky and golden mountains, premium finish\"\n}"
response = http.request(request)
puts response.read_body{
"created": 1795534600,
"id": "tsk_01m8736tvsqp2t27p0k53hjn7z",
"data": [
{
"b64_json": "iVBORw0KGgoAAAANSUhEUgAA...",
"url": "https://hdcdn.agisuitepro.com/o/2026/11/24/example.png"
}
],
"usage": {
"prompt_tokens": 1000,
"total_tokens": 1000,
"input_tokens": 1000,
"output_tokens": 0
}
}Генерация изображений Tencent Hunyuan Hy-Image 3.5
Справочник API преобразования текста в изображение
Справочник API преобразования текста в изображение Tencent Hunyuan Hy-Image 3.5 Preview и игровая площадка — hy-image-v3.5-preview-2k / -4k с фиксированным размером вывода 2048/4096, b64_json по умолчанию и необязательным URL CDN
POST
/
v1
/
images
/
generations
Text-to-image: generate a 2K/4K image from a prompt
curl --request POST \
--url https://api.apiyi.com/v1/images/generations \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data '
{
"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"
}
'import requests
url = "https://api.apiyi.com/v1/images/generations"
payload = {
"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"
}
headers = {
"Authorization": "Bearer <token>",
"Content-Type": "application/json"
}
response = requests.post(url, json=payload, headers=headers)
print(response.text)const options = {
method: 'POST',
headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
body: JSON.stringify({
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'
})
};
fetch('https://api.apiyi.com/v1/images/generations', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.apiyi.com/v1/images/generations",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode([
'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'
]),
CURLOPT_HTTPHEADER => [
"Authorization: Bearer <token>",
"Content-Type: application/json"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"strings"
"net/http"
"io"
)
func main() {
url := "https://api.apiyi.com/v1/images/generations"
payload := strings.NewReader("{\n \"model\": \"hy-image-v3.5-preview-2k\",\n \"prompt\": \"A cinematic movie poster with the Chinese title \\\"Between Mountains and Seas\\\" centered, deep blue night sky and golden mountains, premium finish\"\n}")
req, _ := http.NewRequest("POST", url, payload)
req.Header.Add("Authorization", "Bearer <token>")
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.post("https://api.apiyi.com/v1/images/generations")
.header("Authorization", "Bearer <token>")
.header("Content-Type", "application/json")
.body("{\n \"model\": \"hy-image-v3.5-preview-2k\",\n \"prompt\": \"A cinematic movie poster with the Chinese title \\\"Between Mountains and Seas\\\" centered, deep blue night sky and golden mountains, premium finish\"\n}")
.asString();require 'uri'
require 'net/http'
url = URI("https://api.apiyi.com/v1/images/generations")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n \"model\": \"hy-image-v3.5-preview-2k\",\n \"prompt\": \"A cinematic movie poster with the Chinese title \\\"Between Mountains and Seas\\\" centered, deep blue night sky and golden mountains, premium finish\"\n}"
response = http.request(request)
puts response.read_body{
"created": 1795534600,
"id": "tsk_01m8736tvsqp2t27p0k53hjn7z",
"data": [
{
"b64_json": "iVBORw0KGgoAAAANSUhEUgAA...",
"url": "https://hdcdn.agisuitepro.com/o/2026/11/24/example.png"
}
],
"usage": {
"prompt_tokens": 1000,
"total_tokens": 1000,
"input_tokens": 1000,
"output_tokens": 0
}
}Интерактивная площадка справа поддерживает тестирование в реальном времени. Введите свой API-ключ в Authorization (формат:
Bearer sk-xxx), выберите model, введите prompt, при необходимости выберите response_format и отправьте запрос. Не заполняйте size; обе модели используют фиксированные размеры выходных данных.Когда использовать эту страницу: обычная генерация изображений из текста. Вам нужен только промпт. Для генерации или редактирования на основе эталонного изображения используйте API эталонного изображения.
⚠️ Три важных момента
sizeпереопределяется моделью:-2kвсегда возвращает изображение размером 2048×2048, а-4k— размером 4096×4096. Не пытайтесь изменить разрешение с помощьюsize.nвсегда равно 1: передача значения 2 или 3 всё равно возвращает одно изображение, и тарификация выполняется один раз. Для получения нескольких изображений отправляйте параллельные запросы.- По умолчанию ответы возвращаются в формате base64: размер ответа 2K составляет около 6–8.4 МБ, а ответа 4K — 17.6–20 МБ. Для отображения в веб-интерфейсе передайте
response_format: "url".
Примеры кода
Python (OpenAI SDK)
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 (необработанные запросы)
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
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)
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)
{/* 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 | строка | Да | — | hy-image-v3.5-preview-2k (2048×2048) или hy-image-v3.5-preview-4k (4096×4096) |
prompt | строка | Да | — | Промпт на китайском или английском языке; заключайте текст, который должен появиться на изображении, в кавычки |
response_format | строка | Нет | b64_json | b64_json или url; при недопустимых значениях автоматически используется base64 |
size | — | — | — | Переопределяется моделью; не передавайте |
n | — | — | — | Фиксировано на уровне 1; при других значениях всё равно возвращается одно изображение |
images / image | — | — | — | Не требуется для преобразования текста в изображение; используйте API референсного изображения |
Ограничения и допустимые значения приведены в описаниях полей Playground.
quality, style и output_format не влияют на результат; не отправляйте их.Формат ответа
По умолчаниюresponse_format: "b64_json":
{
"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":
{
"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
}
}
Примечания к ответу
b64_json— это обычный base64 без префиксаdata:image/png;base64,. Декодируйте его напрямую в PNG.- PNG 2K занимает около 4,4–5,7 МБ, а ответ в формате base64 — 6–8,4 МБ; PNG 4K занимает 12,6–18,9 МБ, а ответ в формате base64 — 17,6–20 МБ.
urlвозвращает стабильный URL наhdcdn.agisuitepro.com. HEAD возвращает 200, и<img>работает, но предварительный запрос CORS возвращает 403, поэтому для доступа браузераfetch/ canvas требуется прокси на стороне сервера.usage— это заполнитель, который нельзя использовать для сверки тарификации.
usage не являются данными, подлежащими тарификации: значение prompt_tokens всегда равно 1000, а output_tokens всегда равно 0. Для этой серии взимается фиксированная плата за изображение; используйте счёт в консоли APIYI для просмотра фактических начислений.Тело
application/json
Ответ
Image generated successfully
Была ли эта страница полезной?