curl --request POST \
--url https://api.apiyi.com/v1/images/generations \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data '
{
"model": "gpt-image-2",
"prompt": "Cyberpunk city at night, neon sign closeup, cinematic frame"
}
'import requests
url = "https://api.apiyi.com/v1/images/generations"
payload = {
"model": "gpt-image-2",
"prompt": "Cyberpunk city at night, neon sign closeup, cinematic frame"
}
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: 'gpt-image-2',
prompt: 'Cyberpunk city at night, neon sign closeup, cinematic frame'
})
};
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' => 'gpt-image-2',
'prompt' => 'Cyberpunk city at night, neon sign closeup, cinematic frame'
]),
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\": \"gpt-image-2\",\n \"prompt\": \"Cyberpunk city at night, neon sign closeup, cinematic frame\"\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\": \"gpt-image-2\",\n \"prompt\": \"Cyberpunk city at night, neon sign closeup, cinematic frame\"\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\": \"gpt-image-2\",\n \"prompt\": \"Cyberpunk city at night, neon sign closeup, cinematic frame\"\n}"
response = http.request(request)
puts response.read_body{
"created": 1776832476,
"data": [
{
"b64_json": "iVBORw0KGgoAAAANSUhEUgAA..."
}
],
"usage": {
"input_tokens": 42,
"output_tokens": 6240,
"total_tokens": 6282
}
}텍스트-투-이미지 API 레퍼런스
gpt-image-2 텍스트-투-이미지 API 레퍼런스 및 실시간 테스트 — 유효한 해상도(4K 포함), token 기준 과금
curl --request POST \
--url https://api.apiyi.com/v1/images/generations \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data '
{
"model": "gpt-image-2",
"prompt": "Cyberpunk city at night, neon sign closeup, cinematic frame"
}
'import requests
url = "https://api.apiyi.com/v1/images/generations"
payload = {
"model": "gpt-image-2",
"prompt": "Cyberpunk city at night, neon sign closeup, cinematic frame"
}
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: 'gpt-image-2',
prompt: 'Cyberpunk city at night, neon sign closeup, cinematic frame'
})
};
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' => 'gpt-image-2',
'prompt' => 'Cyberpunk city at night, neon sign closeup, cinematic frame'
]),
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\": \"gpt-image-2\",\n \"prompt\": \"Cyberpunk city at night, neon sign closeup, cinematic frame\"\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\": \"gpt-image-2\",\n \"prompt\": \"Cyberpunk city at night, neon sign closeup, cinematic frame\"\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\": \"gpt-image-2\",\n \"prompt\": \"Cyberpunk city at night, neon sign closeup, cinematic frame\"\n}"
response = http.request(request)
puts response.read_body{
"created": 1776832476,
"data": [
{
"b64_json": "iVBORw0KGgoAAAANSUhEUgAA..."
}
],
"usage": {
"input_tokens": 42,
"output_tokens": 6240,
"total_tokens": 6282
}
}Bearer sk-xxx), prompt를 입력한 다음 크기 / 품질을 선택하고 전송합니다.请求时发生错误: unable to complete request를 표시할 수 있습니다 — 실제로 요청은 성공했습니다; 브라우저가 그렇게 긴 base64 문자열을 렌더링하지 못할 뿐입니다.권장 워크플로(초보자 친화적):- 아래 Python / Node.js / cURL 예제를 복사하여 로컬에서 실행하십시오. 코드는 응답을 자동으로
base64.b64decodes하고 이미지를 파일로 저장합니다. - 브라우저 내 플레이그라운드를 반드시 사용해야 한다면,
size을/를 가장 작은 티어로(예:1024x1024) 설정하고quality을/를low로 설정하여 응답을 줄이십시오.
input_fidelity—gpt-image-2는 고충실도를 강제합니다. 이를 전달하면 400이 반환됩니다. 1.5에서 마이그레이션할 때는 해당 줄만 제거하면 됩니다.background: "transparent"— 투명 배경은 지원되지 않습니다. 투명 처리가 필요하면opaque를 사용하거나 후처리하십시오.
2560×1440를 초과하는 출력은 계속 실험적입니다. 프로덕션에서는 2048x1152 / 2048x2048 / 3840x2160 프리셋을 권장합니다.코드 예제
Python (OpenAI SDK)
from openai import OpenAI
import base64
client = OpenAI(
api_key="sk-your-api-key",
base_url="https://api.apiyi.com/v1"
)
resp = client.images.generate(
model="gpt-image-2",
prompt="Cyberpunk city at night, neon sign closeup, cinematic frame",
size="2048x1152",
quality="high",
output_format="jpeg",
output_compression=85
)
# b64_json is raw base64 (no prefix) — decode and write to file
with open("out.jpg", "wb") as f:
f.write(base64.b64decode(resp.data[0].b64_json))
Python (원시 요청)
import requests
import base64
API_KEY = "sk-your-api-key"
response = requests.post(
"https://api.apiyi.com/v1/images/generations",
headers={
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
},
json={
"model": "gpt-image-2",
"prompt": "Landscape 2K seaside lighthouse at sunset, cinematic frame",
"size": "2048x1152",
"quality": "high"
},
timeout=360 # high + 2K/4K can run 3-5 min; ~120s defaults will frequently false-timeout
).json()
with open("out.png", "wb") as f:
f.write(base64.b64decode(response["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": "gpt-image-2",
"prompt": "Orange tabby cat with sunglasses at a seaside bar, cinematic",
"size": "2048x1152",
"quality": "high",
"output_format": "jpeg",
"output_compression": 85
}'
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 sk-your-api-key'
},
body: JSON.stringify({
model: 'gpt-image-2',
prompt: 'Minimalist line-art cat logo',
size: '1024x1024',
quality: 'medium'
})
});
const { data } = await resp.json();
// b64_json is raw base64 — decode manually
fs.writeFileSync('logo.png', Buffer.from(data[0].b64_json, 'base64'));
브라우저 JavaScript (직접 렌더링)
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: 'gpt-image-2',
prompt: 'Watercolor-style Nordic aurora',
size: '1536x1024',
quality: 'high'
})
});
const { data } = await resp.json();
// Browser rendering needs the data URL prefix prepended manually
document.getElementById('img').src = `data:image/png;base64,${data[0].b64_json}`;
매개변수 참조
| 매개변수 | 유형 | 필수 | 기본값 | 설명 |
|---|---|---|---|---|
model | string | Yes | — | 고정값: gpt-image-2 |
prompt | string | Yes | — | prompt, 중국어와 영어를 모두 지원합니다 |
size | string | No | auto | 출력 크기 — 사전 설정값 또는 제약을 만족하는 사용자 지정값 |
quality | string | No | auto | low / medium / high / auto |
output_format | string | No | png | png / jpeg / webp |
output_compression | int | No | — | 0–100, jpeg / webp에만 사용 |
background | string | No | auto | opaque / auto (지원되지 않음: transparent) |
moderation | string | No | auto | auto / low (저강도 moderation) |
n | int | No | 1 | 1만 지원됩니다 |
standard / hd을 quality에 전달하지 마십시오.** 공식 enum 값 네 가지 low / medium / high / auto만 허용됩니다. 레거시 값은 백엔드 채널마다 일관되지 않게 동작합니다. 때로는 400(invalid_value)으로 즉시 실패하고, 때로는 조용히 무시되어 요청이 auto으로 실행됩니다(비용 예측 불가). 항상 네 가지 공식 값 중 하나를 명시적으로 전달하십시오.응답 형식
{
"created": 1776832476,
"data": [
{
"b64_json": "iVBORw0KGgoAAAANSUhEUgAA..."
}
],
"usage": {
"input_tokens": 17,
"input_tokens_details": {
"image_tokens": 0,
"text_tokens": 17
},
"output_tokens": 196,
"output_tokens_details": {
"image_tokens": 196,
"text_tokens": 0
},
"total_tokens": 213
}
}
data:image/...;base64, 접두사 없이입니다. 클라이언트는 다음을 수행해야 합니다:- 파일 쓰기:
base64.b64decode(b64_str)→ 디스크에 기록 - 브라우저 렌더링:
data:image/png;base64,을 수동으로 앞에 붙입니다
gpt-image-2-all / gpt-image-2-vip도 원시 base64를 반환하지만, 이전 버전에는 접두사가 포함되어 있었습니다 — 모델 간에 코드를 공유할 때는 항상 먼저 startsWith('data:')를 확인하십시오.usage 필드는 이 호출에 대해 실제로 과금된 token 수를 나타냅니다. input_tokens_details / output_tokens_details은 텍스트 token과 이미지 token을 별도로 분리합니다(image_tokens은 일반 text-to-image의 경우 항상 0입니다). 전체 필드 참고와 셀프서비스 비용 계산 공식은 개요 페이지의 각 호출의 실제 token 수를 확인하는 방법을 참조하십시오.인증
API Key obtained from APIYI Console
본문
Model name, fixed as gpt-image-2
gpt-image-2 Prompt text. Supports both Chinese and English. Place scene description at the front for better adherence.
"Cyberpunk city at night, neon sign closeup, cinematic frame"
Output size. Presets: 1024x1024 / 1536x1024 / 1024x1536 / 2048x2048 / 2048x1152 / 3840x2160 / 2160x3840. Also accepts any valid custom size (max edge ≤ 3840, both multiples of 16, ratio ≤ 3:1, total pixels 0.65–8.3MP).
"2048x1152"
Quality tier. low (sketches/batch), medium (daily), high (final/fine text), auto (default)
auto, low, medium, high Output format
png, jpeg, webp Output compression (0–100), only effective for jpeg/webp
0 <= x <= 10085
Background mode. auto (default) or opaque. Not supported: transparent
auto, opaque Moderation strength. auto (default) or low
auto, low Number of images. This model only supports 1
1 이 페이지가 도움이 되었나요?