Text-to-image: generate an image from a text prompt
curl --request POST \
--url https://api.apiyi.com/v1/images/generations \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data '
{
"model": "MAI-Image-2.6-Flash",
"prompt": "A traditional teahouse storefront with a wooden sign that reads \"Welcome\", red lanterns, warm dusk light, photorealistic"
}
'import requests
url = "https://api.apiyi.com/v1/images/generations"
payload = {
"model": "MAI-Image-2.6-Flash",
"prompt": "A traditional teahouse storefront with a wooden sign that reads \"Welcome\", red lanterns, warm dusk light, photorealistic"
}
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: 'MAI-Image-2.6-Flash',
prompt: 'A traditional teahouse storefront with a wooden sign that reads "Welcome", red lanterns, warm dusk light, photorealistic'
})
};
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' => 'MAI-Image-2.6-Flash',
'prompt' => 'A traditional teahouse storefront with a wooden sign that reads "Welcome", red lanterns, warm dusk light, photorealistic'
]),
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\": \"MAI-Image-2.6-Flash\",\n \"prompt\": \"A traditional teahouse storefront with a wooden sign that reads \\\"Welcome\\\", red lanterns, warm dusk light, photorealistic\"\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\": \"MAI-Image-2.6-Flash\",\n \"prompt\": \"A traditional teahouse storefront with a wooden sign that reads \\\"Welcome\\\", red lanterns, warm dusk light, photorealistic\"\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\": \"MAI-Image-2.6-Flash\",\n \"prompt\": \"A traditional teahouse storefront with a wooden sign that reads \\\"Welcome\\\", red lanterns, warm dusk light, photorealistic\"\n}"
response = http.request(request)
puts response.read_body{
"created": 1790999642,
"data": [
{
"b64_json": "<string>"
}
],
"usage": {
"prompt_tokens": 1000,
"total_tokens": 1000,
"output_tokens": 0
}
}MAI-Image 2.6 이미지 생성 및 편집
텍스트-이미지 API 레퍼런스
라이브 플레이그라운드가 포함된 MAI-Image 2.6 텍스트-이미지 API 레퍼런스 — 텍스트 prompt로 생성하고, 최대 1536×1536 영역까지 사용자 지정 너비/높이를 설정할 수 있으며, 항상 PNG base64를 반환합니다
POST
/
v1
/
images
/
generations
Text-to-image: generate an image from a text prompt
curl --request POST \
--url https://api.apiyi.com/v1/images/generations \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data '
{
"model": "MAI-Image-2.6-Flash",
"prompt": "A traditional teahouse storefront with a wooden sign that reads \"Welcome\", red lanterns, warm dusk light, photorealistic"
}
'import requests
url = "https://api.apiyi.com/v1/images/generations"
payload = {
"model": "MAI-Image-2.6-Flash",
"prompt": "A traditional teahouse storefront with a wooden sign that reads \"Welcome\", red lanterns, warm dusk light, photorealistic"
}
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: 'MAI-Image-2.6-Flash',
prompt: 'A traditional teahouse storefront with a wooden sign that reads "Welcome", red lanterns, warm dusk light, photorealistic'
})
};
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' => 'MAI-Image-2.6-Flash',
'prompt' => 'A traditional teahouse storefront with a wooden sign that reads "Welcome", red lanterns, warm dusk light, photorealistic'
]),
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\": \"MAI-Image-2.6-Flash\",\n \"prompt\": \"A traditional teahouse storefront with a wooden sign that reads \\\"Welcome\\\", red lanterns, warm dusk light, photorealistic\"\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\": \"MAI-Image-2.6-Flash\",\n \"prompt\": \"A traditional teahouse storefront with a wooden sign that reads \\\"Welcome\\\", red lanterns, warm dusk light, photorealistic\"\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\": \"MAI-Image-2.6-Flash\",\n \"prompt\": \"A traditional teahouse storefront with a wooden sign that reads \\\"Welcome\\\", red lanterns, warm dusk light, photorealistic\"\n}"
response = http.request(request)
puts response.read_body{
"created": 1790999642,
"data": [
{
"b64_json": "<string>"
}
],
"usage": {
"prompt_tokens": 1000,
"total_tokens": 1000,
"output_tokens": 0
}
}오른쪽의 대화형 플레이그라운드에서 온라인으로 테스트할 수 있습니다. Authorization에 API 키를 입력하고(형식:
Bearer sk-xxx), model을 선택하고, prompt를 입력한 다음, 필요에 따라 width / height를 설정하고 전송합니다.사용 사례: 이 페이지는 텍스트에서 이미지를 생성하는 용도로만 사용됩니다. 기존 이미지를 수정하려면 이미지 편집 API를 사용하십시오.
⚠️ 세 매개변수는 400을 반환합니다이 시리즈는
response_format, seed 또는 negative_prompt을 허용하지 않으며, 이 중 하나라도 전송하면 400 Invalid parameters: xxx을 반환합니다. gpt-image / DALL·E에서 마이그레이션하는 경우 먼저 response_format를 제거하십시오. 응답은 항상 data[0].b64_json입니다.⚠️ size가 아닌 width + height를 사용하십시오이 엔드포인트는
size을 자동으로 무시하며 항상 1024×1024로 렌더링합니다. 정수 width + height을 사용하십시오(항상 함께 사용): 각 변은 768 이상이어야 하며, width × height는 2,359,296 이하이어야 합니다(1536×1536 면적).모든 이미지 API는 동기식입니다. 비동기 작업 ID는 없습니다. 클라이언트의 연결이 끊기면 결과는 손실되지만 요청에는 여전히 과금됩니다. 1024×1024 이미지는 Flash에서 약 17초, 2.6에서 약 30초가 걸립니다. 클라이언트 타임아웃을 Flash에서는 최소 120초, 2.6에서는 180초로 설정하십시오. 이미지 API 필수 사항 및 모범 사례를 참조하십시오.
코드 예제
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=180.0 # synchronous call, give it enough time
)
resp = client.images.generate(
model="MAI-Image-2.6-Flash",
prompt='A traditional teahouse storefront with a wooden sign that reads "Welcome", red lanterns, warm dusk light, photorealistic',
# width / height are not standard OpenAI SDK fields, so pass them via extra_body
# Do not pass response_format: it returns 400
extra_body={"width": 1024, "height": 1024}
)
with open("out.png", "wb") as f:
f.write(base64.b64decode(resp.data[0].b64_json))
Python (requests)
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": "MAI-Image-2.6",
"prompt": "A red fox sitting on a mossy rock in a misty forest, soft morning light, photorealistic",
"width": 1536,
"height": 1024
},
timeout=180
)
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": "MAI-Image-2.6-Flash",
"prompt": "A minimalist coffee shop poster with the headline \"Autumn Special\" at the top, warm brown palette",
"width": 1024,
"height": 1536
}' | 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: 'MAI-Image-2.6-Flash',
prompt: 'A serene Japanese garden with cherry blossoms, koi pond, golden hour',
width: 1792,
height: 1008 // 16:9; width × height must not exceed 2,359,296
}),
signal: AbortSignal.timeout(120000)
});
const data = await resp.json();
fs.writeFileSync('out.png', Buffer.from(data.data[0].b64_json, 'base64'));
여러 이미지가 필요한 경우: 요청을 병렬로 전송
텍스트-이미지 엔드포인트는 호출당 이미지 1개를 반환합니다(n는 효과가 없습니다). 따라서 요청을 병렬로 실행합니다:
import base64, os, requests
from concurrent.futures import ThreadPoolExecutor
def gen(i):
r = requests.post(
"https://api.apiyi.com/v1/images/generations",
headers={"Authorization": f"Bearer {os.environ['APIYI_API_KEY']}"},
json={"model": "MAI-Image-2.6-Flash", "prompt": "a watercolor lighthouse at dusk"},
timeout=120
)
r.raise_for_status()
open(f"out-{i}.png", "wb").write(base64.b64decode(r.json()["data"][0]["b64_json"]))
with ThreadPoolExecutor(max_workers=4) as pool:
list(pool.map(gen, range(4)))
매개변수 참조
| 매개변수 | 유형 | 필수 | 기본값 | 설명 |
|---|---|---|---|---|
model | string | ✅ | — | MAI-Image-2.6 ($0.12/이미지) 또는 MAI-Image-2.6-Flash ($0.06/이미지), 대소문자를 구분합니다 |
prompt | string | ✅ | — | 모든 언어의 prompt입니다. 이미지에 표시할 텍스트는 따옴표로 묶습니다 |
width | integer | ❌ | 1024 | 출력 너비입니다. ≥ 768이어야 하며, height과 함께 전송해야 하고, 16의 배수로 내림합니다 |
height | integer | ❌ | 1024 | 출력 높이입니다. ≥ 768이어야 하며, 너비 × 높이 ≤ 2,359,296이어야 합니다 |
response_format | — | — | — | 400을 반환합니다. 응답은 항상 b64_json입니다 |
seednegative_prompt | — | — | — | 400을 반환합니다 |
size | — | — | — | 이 엔드포인트에서는 자동으로 무시됩니다 |
n | — | — | — | 이 엔드포인트에서는 적용되지 않으며, 항상 이미지 1개를 반환합니다 |
quality, output_format, background, style 및 기타 OpenAI 스타일 필드는 자동으로 무시됩니다. 출력은 항상 PNG입니다.응답 형식
{
"created": 1790999642,
"data": [
{
"b64_json": "iVBORw0KGgoAAAANSUhEUgAABAAAAAQACAIAAADwf7zU..."
}
],
"usage": {
"prompt_tokens": 1000,
"total_tokens": 1000,
"input_tokens": 1000,
"output_tokens": 0
}
}
응답 필드
b64_json는data:image/png;base64,접두사가 없는 plain base64입니다. 직접 디코딩하면 PNG를 얻을 수 있습니다.url필드는 없으며,revised_prompt도 없습니다.- 1024×1024 PNG는 약 1.5–1.7MB( base64로는 2.1–2.3MB)이며, 1536×1536은 약 4–5MB입니다. 클라이언트의 응답 크기 제한을 확인하십시오.
usage와 과금을 대조하지 마십시오: prompt_tokens은 항상 이미지 수의 1000배이고 output_tokens은 항상 0이며, 이는 플레이스홀더입니다. 이 시리즈는 이미지당 과금되며, APIYI 콘솔의 청구 내역이 기준이 됩니다.본문
application/json
응답
Image generated
이 페이지가 도움이 되었나요?