> ## 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>
  所有接口均需要使用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 参数）

当需要精确控制像素尺寸时，可使用 `size` 参数代替 `aspect_ratio` + `resolution` 组合。

**有效范围：** 总像素 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>
