> ## Documentation Index
> Fetch the complete documentation index at: https://docs.aireiter.com/llms.txt
> Use this file to discover all available pages before exploring further.

# GPT-Image-2 이미지 생성

> - 비동기 처리 모드, 작업 ID를 반환하여 이후 조회에 사용
- OpenAI Images 호환 프로토콜 기반, 텍스트 생성 이미지 / 이미지 변환 지원
- 13가지 이미지 비율 지원, aspect_ratio 필드로 전달
- resolution 단계 필드 추가, 1K / 2K / 4K 해상도 선택 지원(4K 전 비율 지원)
- size 필드 추가, 사용자 정의 픽셀 크기 지원(aspect_ratio / resolution과 상호 배타적, 총 픽셀 수 ≥ 2,088,960이어야 정확한 이미지 생성 가능)
- 참조 이미지는 최대 10장, URL과 base64 혼용 가능
- 제출된 prompt는 플랫폼 민감어 / 보안 심사를 통과하며, 위반 내용은 즉시 거부됨


export const apiKeyUrl = 'https://aireiter.com/keys';

## Authorizations

<ParamField header="Authorization" type="string" required>
  모든 API는 Bearer Token을 사용하여 인증해야 합니다.

  API Key 받기:

  <a href={apiKeyUrl} target="_blank">API Key 관리 페이지</a>에 접속하여 API Key를 받으세요.

  요청 헤더에 다음을 추가하세요:

  ```
  Authorization: Bearer YOUR_API_KEY
  ```
</ParamField>

## Body

<ParamField body="model" type="string" required>
  모델 이름

  고정 값: `"gpt_image_2"`
</ParamField>

<ParamField body="params" type="object" required>
  모델 파라미터 객체

  <Expandable title="params 객체 속성">
    <ParamField body="prompt" type="string" required>
      이미지 생성을 위한 텍스트 설명

      * 한중영 지원, 자세한 설명 권장
      * 제출 전 플랫폼 민감 단어 / 보안 검토 진행, 위반 내용 적발 시 오류 반환
    </ParamField>

    <ParamField body="image_url" type="string[]">
      참조 이미지 배열, 전달 시 이미지 생성 모드로 동작

      * 최대 10장의 참조 이미지
      * 다음 두 가지 형식 지원:
        1. 공개 접근 가능한 URL
        2. Base64 인코딩 형식
           * 반드시 완전한 Data URI 형식 사용: `data:image/{형식};base64,{base64데이터}`
           * 지원 이미지 형식: jpeg, png, webp
           * 예시: `data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABg...`
           * ⚠️ 주의: 반드시 `data:image/jpeg;base64,` 접두어 포함
    </ParamField>

    <ParamField body="aspect_ratio" type="string" default="auto">
      이미지 생성 비율

      기본값은 `resolution`에 따라 변동:

      * `resolution`이 `1K` / `2K`일 때 미전달 시 기본값 `auto`
      * `resolution`이 `4K`일 때 미전달 시 기본값 `16:9`

      다음 값 지원:

      * `auto` - 가장 적합한 비율 자동 선택
      * `1:1` - 정사각형
      * `16:9` / `9:16` - 와이드 가로 / 세로
      * `4:3` / `3:4` - 표준 가로 / 세로
      * `3:2` / `2:3` - 클래식 가로 / 세로
      * `5:4` / `4:5` - 근사 정사각형 가로 / 세로
      * `2:1` / `1:2` - 와이드 가로 / 롱 세로
      * `21:9` / `9:21` - 초와이드 가로 / 초롱 세로

      <Warning>
        비율은 문자열 또는 `auto`만 지원; 픽셀 크기(예: `1024x1024`) 전달 시 오류
      </Warning>
    </ParamField>

    <ParamField body="resolution" type="string" default="1K">
      해상도 단계

      실제 이미지 선명도 제어:

      * `1K` - 1024 기준, 비용 절감 일상용(기본값)
      * `2K` - 2048 기준, 포스터 / 고해상도 필요에 적합
      * `4K` - 3840 기준, **모든 13가지 비율 지원**

      <Warning>
        `size` 전달 시, `resolution`과 `aspect_ratio` 동시에 전달 불가, 400 반환
      </Warning>
    </ParamField>

    <ParamField body="size" type="string">
      사용자 정의 픽셀 크기 (`aspect_ratio` / `resolution`과 **상호 배타적**)

      형식은 `가로x세로`, 예: `2048x1536`, `3840x2160`.

      **사용 제한:**

      * 형식은 반드시 `^\d+x\d+$` (예: `2048x1536`), 다른 작성법은 미지원
      * `aspect_ratio`, `resolution`과 상호 배타적, 세 개 중 하나만 선택; 동시에 전달 시 400 오류
      * 총 픽셀 수(가로 × 세로)는 **655,360 \~ 8,294,400** 범위여야 함

      **실제 픽셀 하한:**

      | 총 픽셀 범위              | 상위 시스템 동작                                    |
      | -------------------- | -------------------------------------------- |
      | ≥ 2,088,960 (약 2.0M) | 입력한 `size`에 따라 정확히 출력 ✅                      |
      | \< 2,088,960         | 약 1.57M 비슷한 비율로 조용히 대체(즉, `size` 미전달과 동일) ⚠️ |

      <Warning>
        총 픽셀이 약 2,088,960 이하일 경우, 상위 시스템은 오류를 내지 않으나 출력 크기를 조용히 변경함. 정확한 제어가 필요하면 **총 픽셀 수 ≥ 2,088,960** 권장.

        낮은 크기 필요 시 `aspect_ratio` + `resolution=1K` 조합 사용 권장.
      </Warning>

      **선택 권장:**

      | 요구사항            | 추천 방식                               |
      | --------------- | ----------------------------------- |
      | 픽셀 크기 정확 제어     | `size`, 그리고 총 픽셀 수 ≥ 2,088,960      |
      | 작은 크기(\< 2M 픽셀) | `aspect_ratio` + `resolution=1K`    |
      | 중대형 임의 비율       | `size`, 2K / 4K 범위에서 임의 비율 정확 출력 가능 |
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="out_task_id" type="string" required>
  요청자 작업 ID

  사용자 정의 작업 식별자, 필수
</ParamField>

## 크기 × 해상도 매핑 테이블

`aspect_ratio × resolution` → 실제 픽셀 (13 비율 × 3 단계):

| aspect\_ratio | `1K`                  | `2K`      | `4K`          |
| ------------- | --------------------- | --------- | ------------- |
| `1:1`         | 1024×1024 / 1254×1254 | 2048×2048 | **2880×2880** |
| `3:2`         | 1536×1024             | 2048×1360 | **3520×2336** |
| `2:3`         | 1024×1536             | 1360×2048 | **2336×3520** |
| `4:3`         | 1024×768              | 2048×1536 | **3312×2480** |
| `3:4`         | 768×1024              | 1536×2048 | **2480×3312** |
| `5:4`         | 1280×1024 / 1448×1086 | 2560×2048 | **3216×2576** |
| `4:5`         | 1024×1280 / 1122×1402 | 2048×2560 | **2576×3216** |
| `16:9`        | 1536×864 / 1672×941   | 2048×1152 | **3840×2160** |
| `9:16`        | 864×1536 / 941×1672   | 1152×2048 | **2160×3840** |
| `2:1`         | 2048×1024 / 1774×887  | 2688×1344 | **3840×1920** |
| `1:2`         | 1024×2048 / 887×1774  | 1344×2688 | **1920×3840** |
| `21:9`        | 2016×864 / 1915×821   | 2688×1152 | **3840×1648** |
| `9:21`        | 864×2016 / 821×1915   | 1152×2688 | **1648×3840** |

> `3:2` / `2:3` @ 2K는 실제로 2048×1360 (근사 비율, 오차 \< 0.5%); 4K는 이제 모든 13개 비율을 지원합니다.

## 사용자 정의 크기(size 매개변수)

픽셀 크기를 정확히 제어해야 할 때, `aspect_ratio` + `resolution` 조합 대신 `size` 매개변수를 사용할 수 있습니다.

**유효 범위:** 총 픽셀 655,360 \~ 8,294,400(상위 공식 제한)

**실제 유효 하한:** 총 픽셀 ≥ **2,088,960**(약 1440×1452 또는 2048×1020 동등 면적)

이 하한 미만에서는 상위에서 오류를 반환하지 않지만, 조용히 약 1.57M 픽셀 크기의 비슷한 비율로 대체됩니다.

### 자주 사용하는 size 예시

| size 값      | 총 픽셀      | 추천 용도        |
| ----------- | --------- | ------------ |
| `2048x2048` | 4,194,304 | 정사각형 고해상도    |
| `2048x1536` | 3,145,728 | 4:3 가로형      |
| `1536x2048` | 3,145,728 | 3:4 세로형      |
| `2048x1152` | 2,359,296 | 16:9 가로형     |
| `1152x2048` | 2,359,296 | 9:16 세로형     |
| `3840x2160` | 8,294,400 | 4K 16:9(최상위) |
| `2688x1344` | 3,612,672 | 2:1 와이드 가로형  |

<Warning>
  **`aspect_ratio`나 `resolution`과 동시에 전달하지 마십시오**, 그렇지 않으면 400을 반환합니다.
</Warning>

## Response

<ResponseField name="out_task_id" type="string">
  요청자 작업 ID로 결과 조회에 사용할 수 있음
</ResponseField>

<ResponseField name="status" type="string">
  초기 상태, 고정 값 `"pending"`
</ResponseField>

<ResponseField name="estimated_credits" type="number">
  예상 소모 크레딧
</ResponseField>

<ResponseField name="created_at" type="string">
  생성 시간(ISO 형식)
</ResponseField>

<RequestExample>
  ```bash cURL（aspect_ratio） theme={null}
  curl --request POST \
    --url https://aireiter.com/api/openapi/submit \
    --header 'Authorization: Bearer <token>' \
    --header 'Content-Type: application/json' \
    --data '{
      "model": "gpt_image_2",
      "params": {
        "prompt": "한 마리의 주황색 고양이가 창턱에 앉아 석양을 바라보는 수채화 스타일",
        "aspect_ratio": "16:9"
      },
      "out_task_id": "my_task_123456"
    }'
  ```

  ```bash cURL（size 사용자 정의 크기） theme={null}
  curl --request POST \
    --url https://aireiter.com/api/openapi/submit \
    --header 'Authorization: Bearer <token>' \
    --header 'Content-Type: application/json' \
    --data '{
      "model": "gpt_image_2",
      "params": {
        "prompt": "한 마리의 주황색 고양이가 창턱에 앉아 석양을 바라보는 수채화 스타일",
        "size": "2048x1152"
      },
      "out_task_id": "my_task_size_001"
    }'
  ```

  ```python Python theme={null}
  import requests

  url = "https://aireiter.com/api/openapi/submit"

  payload = {
      "model": "gpt_image_2",
      "params": {
          "prompt": "한 마리의 주황색 고양이가 창턱에 앉아 석양을 바라보는 수채화 스타일",
          "aspect_ratio": "16:9"
      },
      "out_task_id": "my_task_123456"
  }

  headers = {
      "Authorization": "Bearer <token>",
      "Content-Type": "application/json"
  }

  response = requests.post(url, json=payload, headers=headers)

  print(response.json())
  ```

  ```javascript JavaScript theme={null}
  const url = "https://aireiter.com/api/openapi/submit";

  const payload = {
    model: "gpt_image_2",
    params: {
      prompt: "한 마리의 주황색 고양이가 창턱에 앉아 석양을 바라보는 수채화 스타일",
      aspect_ratio: "16:9"
    },
    out_task_id: "my_task_123456"
  };

  const headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
  };

  fetch(url, {
    method: "POST",
    headers: headers,
    body: JSON.stringify(payload)
  })
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));
  ```

  ```go Go theme={null}
  package main

  import (
      "bytes"
      "encoding/json"
      "fmt"
      "io/ioutil"
      "net/http"
  )

  func main() {
      url := "https://aireiter.com/api/openapi/submit"

      payload := map[string]interface{}{
          "model": "gpt_image_2",
          "params": map[string]interface{}{
              "prompt":       "한 마리의 주황색 고양이가 창턱에 앉아 석양을 바라보는 수채화 스타일",
              "aspect_ratio": "16:9",
          },
          "out_task_id": "my_task_123456",
      }

      jsonData, _ := json.Marshal(payload)

      req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
      req.Header.Set("Authorization", "Bearer <token>")
      req.Header.Set("Content-Type", "application/json")

      client := &http.Client{}
      resp, err := client.Do(req)
      if err != nil {
          panic(err)
      }
      defer resp.Body.Close()

      body, _ := ioutil.ReadAll(resp.Body)
      fmt.Println(string(body))
  }
  ```

  ```java Java theme={null}
  import java.net.http.HttpClient;
  import java.net.http.HttpRequest;
  import java.net.http.HttpResponse;
  import java.net.URI;

  public class Main {
      public static void main(String[] args) throws Exception {
          String url = "https://aireiter.com/api/openapi/submit";

          String payload = """
          {
            "model": "gpt_image_2",
            "params": {
              "prompt": "한 마리의 주황색 고양이가 창턱에 앉아 석양을 바라보는 수채화 스타일",
              "aspect_ratio": "16:9"
            },
            "out_task_id": "my_task_123456"
          }
          """;

          HttpClient client = HttpClient.newHttpClient();
          HttpRequest request = HttpRequest.newBuilder()
              .uri(URI.create(url))
              .header("Authorization", "Bearer <token>")
              .header("Content-Type", "application/json")
              .POST(HttpRequest.BodyPublishers.ofString(payload))
              .build();

          HttpResponse<String> response = client.send(request,
              HttpResponse.BodyHandlers.ofString());

          System.out.println(response.body());
      }
  }
  ```

  ```php PHP theme={null}
  <?php

  $url = "https://aireiter.com/api/openapi/submit";

  $payload = [
      "model" => "gpt_image_2",
      "params" => [
          "prompt" => "한 마리의 주황색 고양이가 창턱에 앉아 석양을 바라보는 수채화 스타일",
          "aspect_ratio" => "16:9"
      ],
      "out_task_id" => "my_task_123456"
  ];

  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
  curl_setopt($ch, CURLOPT_HTTPHEADER, [
      "Authorization: Bearer <token>",
      "Content-Type: application/json"
  ]);

  $response = curl_exec($ch);
  curl_close($ch);

  echo $response;
  ?>
  ```

  ```ruby Ruby theme={null}
  require 'net/http'
  require 'json'
  require 'uri'

  url = URI("https://aireiter.com/api/openapi/submit")

  payload = {
    model: "gpt_image_2",
    params: {
      prompt: "한 마리의 주황색 고양이가 창턱에 앉아 석양을 바라보는 수채화 스타일",
      aspect_ratio: "16:9"
    },
    out_task_id: "my_task_123456"
  }

  http = Net::HTTP.new(url.host, url.port)

  request = Net::HTTP::Post.new(url)
  request["Authorization"] = "Bearer <token>"
  request["Content-Type"] = "application/json"
  request.body = payload.to_json

  response = http.request(request)
  puts response.body
  ```

  ```swift Swift theme={null}
  import Foundation

  let url = URL(string: "https://aireiter.com/api/openapi/submit")!

  let payload: [String: Any] = [
      "model": "gpt_image_2",
      "params": [
          "prompt": "한 마리의 주황색 고양이가 창턱에 앉아 석양을 바라보는 수채화 스타일",
          "aspect_ratio": "16:9"
      ],
      "out_task_id": "my_task_123456"
  ]

  var request = URLRequest(url: url)
  request.httpMethod = "POST"
  request.setValue("Bearer <token>", forHTTPHeaderField: "Authorization")
  request.setValue("application/json", forHTTPHeaderField: "Content-Type")
  request.httpBody = try? JSONSerialization.data(withJSONObject: payload)

  let task = URLSession.shared.dataTask(with: request) { data, response, error in
      if let error = error {
          print("Error: \(error)")
          return
      }

      if let data = data, let responseString = String(data: data, encoding: .utf8) {
          print(responseString)
      }
  }

  task.resume()
  ```

  ```csharp C# theme={null}
  using System;
  using System.Net.Http;
  using System.Text;
  using System.Threading.Tasks;

  class Program
  {
      static async Task Main(string[] args)
      {
          var url = "https://aireiter.com/api/openapi/submit";

          var payload = @"{
              ""model"": ""gpt_image_2"",
              ""params"": {
                  ""prompt"": ""한 마리의 주황색 고양이가 창턱에 앉아 석양을 바라보는 수채화 스타일"",
                  ""aspect_ratio"": ""16:9""
              },
              ""out_task_id"": ""my_task_123456""
          }";

          using var client = new HttpClient();
          client.DefaultRequestHeaders.Add("Authorization", "Bearer <token>");

          var content = new StringContent(payload, Encoding.UTF8, "application/json");
          var response = await client.PostAsync(url, content);
          var result = await response.Content.ReadAsStringAsync();

          Console.WriteLine(result);
      }
  }
  ```

  ```c C theme={null}
  #include <stdio.h>
  #include <curl/curl.h>

  int main(void) {
      CURL *curl;
      CURLcode res;

      curl_global_init(CURL_GLOBAL_DEFAULT);
      curl = curl_easy_init();

      if(curl) {
          const char *url = "https://aireiter.com/api/openapi/submit";
          const char *payload = "{"
              "\"model\":\"gpt_image_2\","
              "\"params\":{"
                  "\"prompt\":\"한 마리의 주황색 고양이가 창턱에 앉아 석양을 바라보는 수채화 스타일\","
                  "\"aspect_ratio\":\"16:9\""
              "},"
              "\"out_task_id\":\"my_task_123456\""
          "}";

          struct curl_slist *headers = NULL;
          headers = curl_slist_append(headers, "Authorization: Bearer <token>");
          headers = curl_slist_append(headers, "Content-Type: application/json");

          curl_easy_setopt(curl, CURLOPT_URL, url);
          curl_easy_setopt(curl, CURLOPT_POSTFIELDS, payload);
          curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

          res = curl_easy_perform(curl);

          if(res != CURLE_OK) {
              fprintf(stderr, "curl_easy_perform() failed: %s\n",
                      curl_easy_strerror(res));
          }

          curl_slist_free_all(headers);
          curl_easy_cleanup(curl);
      }

      curl_global_cleanup();
      return 0;
  }
  ```

  ```objectivec Objective-C theme={null}
  #import <Foundation/Foundation.h>

  int main(int argc, const char * argv[]) {
      @autoreleasepool {
          NSURL *url = [NSURL URLWithString:@"https://aireiter.com/api/openapi/submit"];

          NSDictionary *payload = @{
              @"model": @"gpt_image_2",
              @"params": @{
                  @"prompt": @"한 마리의 주황색 고양이가 창턱에 앉아 석양을 바라보는 수채화 스타일",
                  @"aspect_ratio": @"16:9"
              },
              @"out_task_id": @"my_task_123456"
          };

          NSError *error;
          NSData *jsonData = [NSJSONSerialization dataWithJSONObject:payload
                                                            options:0
                                                              error:&error];

          NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
          [request setHTTPMethod:@"POST"];
          [request setValue:@"Bearer <token>" forHTTPHeaderField:@"Authorization"];
          [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
          [request setHTTPBody:jsonData];

          NSURLSessionDataTask *task = [[NSURLSession sharedSession]
              dataTaskWithRequest:request
              completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                  if (error) {
                      NSLog(@"Error: %@", error);
                      return;
                  }
                  NSString *result = [[NSString alloc] initWithData:data
                                                          encoding:NSUTF8StringEncoding];
                  NSLog(@"%@", result);
              }];

          [task resume];
          [[NSRunLoop mainRunLoop] run];
      }
      return 0;
  }
  ```

  ```ocaml OCaml theme={null}
  (* Requires cohttp and yojson libraries *)
  open Lwt
  open Cohttp
  open Cohttp_lwt_unix

  let url = "https://aireiter.com/api/openapi/submit"

  let payload = {|{
    "model": "gpt_image_2",
    "params": {
      "prompt": "한 마리의 주황색 고양이가 창턱에 앉아 석양을 바라보는 수채화 스타일",
      "aspect_ratio": "16:9"
    },
    "out_task_id": "my_task_123456"
  }|}

  let () =
    let headers = Header.init ()
      |> fun h -> Header.add h "Authorization" "Bearer <token>"
      |> fun h -> Header.add h "Content-Type" "application/json"
    in
    let body = Cohttp_lwt.Body.of_string payload in

    let response = Client.post ~headers ~body (Uri.of_string url) >>= fun (resp, body) ->
      body |> Cohttp_lwt.Body.to_string >|= fun body_str ->
      print_endline body_str
    in
    Lwt_main.run response
  ```

  ```dart Dart theme={null}
  import 'dart:convert';
  import 'package:http/http.dart' as http;

  void main() async {
    final url = Uri.parse('https://aireiter.com/api/openapi/submit');

    final payload = {
      'model': 'gpt_image_2',
      'params': {
        'prompt': '한 마리의 주황색 고양이가 창턱에 앉아 석양을 바라보는 수채화 스타일',
        'aspect_ratio': '16:9'
      },
      'out_task_id': 'my_task_123456'
    };

    final response = await http.post(
      url,
      headers: {
        'Authorization': 'Bearer <token>',
        'Content-Type': 'application/json'
      },
      body: jsonEncode(payload),
    );

    print(response.body);
  }
  ```

  ```r R theme={null}
  library(httr)
  library(jsonlite)

  url <- "https://aireiter.com/api/openapi/submit"

  payload <- list(
    model = "gpt_image_2",
    params = list(
      prompt = "한 마리의 주황색 고양이가 창턱에 앉아 석양을 바라보는 수채화 스타일",
      aspect_ratio = "16:9"
    ),
    out_task_id = "my_task_123456"
  )

  response <- POST(
    url,
    add_headers(
      Authorization = "Bearer <token>",
      `Content-Type` = "application/json"
    ),
    body = toJSON(payload, auto_unbox = TRUE),
    encode = "raw"
  )

  cat(content(response, "text"))
  ```
</RequestExample>

<ResponseExample>
  ```json 200 theme={null}
  {
      "statusCode": 200,
      "message": "",
      "data": {
          "out_task_id": "my_task_123456",
          "status": "pending",
          "estimated_credits": 100,
          "created_at": "2025-12-22T06:03:28.242Z"
      }
  }
  ```

  ```json 400 theme={null}
  {
      "statusCode": 400,
      "message": "요청 파라미터가 유효하지 않음",
      "ok": false
  }
  ```

  ```json 401 theme={null}
  {
    "error": {
      "code": 401,
      "message": "인증 실패, API 키를 확인하세요"
    }
  }
  ```

  ```json 433 theme={null}
  {
    "error": {
      "code": 433,
      "message": "계정 잔액 부족, 충전 후 다시 시도하세요"
    }
  }
  ```

  ```json 500 theme={null}
  {
    "error": {
      "code": 500,
      "message": "서버 내부 오류, 잠시 후 다시 시도하세요"
    }
  }
  ```
</ResponseExample>
