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

# GPT-Image-2 画像生成

>  - 非同期処理モード、後続のクエリ用にタスクIDを返します
- OpenAI Images 互換プロトコルに基づき、テキストから画像 / 画像から画像をサポート
- `size` フィールドで 15 種類の比率をサポート
- `resolution`（`1k` / `2k` / `4k`）で実際の出力ピクセル段階を制御

- 参照画像は最大 16 枚、URL と base64 の混在をサポート
- 解像度段階（1K / 2K / 4K）に応じて課金 

<Info>
  **モデル名互換のお知らせ**：本エンドポイントはエイリアス `gpt-image-2-ext` にも対応しており、`gpt-image-2` と同等です。両者は互換的に使用でき、効果は同一です。
</Info>

<RequestExample>
  ```bash cURL theme={null}
  # model には "gpt-image-2" を指定でき、エイリアス "gpt-image-2-ext" にも対応しています
  curl --request POST \
    --url https://api.apimart.ai/v1/images/generations \
    --header 'Authorization: Bearer <token>' \
    --header 'Content-Type: application/json' \
    --data '{
      "model": "gpt-image-2",
      "prompt": "窓辺に座って夕日を見つめる茶トラ猫、水彩画風",
      "n": 1,
      "size": "16:9",
      "resolution": "2k"
    }'
  ```

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

  url = "https://api.apimart.ai/v1/images/generations"

  payload = {
      "model": "gpt-image-2",
      "prompt": "窓辺に座って夕日を見つめる茶トラ猫、水彩画風",
      "n": 1,
      "size": "16:9",
      "resolution": "2k"
  }

  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://api.apimart.ai/v1/images/generations";

  const payload = {
    model: "gpt-image-2",
    prompt: "窓辺に座って夕日を見つめる茶トラ猫、水彩画風",
    n: 1,
    size: "16:9",
    resolution: "2k"
  };

  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://api.apimart.ai/v1/images/generations"

      payload := map[string]interface{}{
          "model":      "gpt-image-2",
          "prompt":     "窓辺に座って夕日を見つめる茶トラ猫、水彩画風",
          "n":          1,
          "size":       "16:9",
          "resolution": "2k",
      }

      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://api.apimart.ai/v1/images/generations";

          String payload = """
          {
            "model": "gpt-image-2",
            "prompt": "窓辺に座って夕日を見つめる茶トラ猫、水彩画風",
            "n": 1,
            "size": "16:9",
            "resolution": "2k"
          }
          """;

          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://api.apimart.ai/v1/images/generations";

  $payload = [
      "model" => "gpt-image-2",
      "prompt" => "窓辺に座って夕日を見つめる茶トラ猫、水彩画風",
      "n" => 1,
      "size" => "16:9",
      "resolution" => "2k"
  ];

  $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://api.apimart.ai/v1/images/generations")

  payload = {
    model: "gpt-image-2",
    prompt: "窓辺に座って夕日を見つめる茶トラ猫、水彩画風",
    n: 1,
    size: "16:9",
    resolution: "2k"
  }

  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 = payload.to_json

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

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

  let url = URL(string: "https://api.apimart.ai/v1/images/generations")!

  let payload: [String: Any] = [
      "model": "gpt-image-2",
      "prompt": "窓辺に座って夕日を見つめる茶トラ猫、水彩画風",
      "n": 1,
      "size": "16:9",
      "resolution": "2k"
  ]

  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://api.apimart.ai/v1/images/generations";

          var payload = @"{
              ""model"": ""gpt-image-2"",
              ""prompt"": ""窓辺に座って夕日を見つめる茶トラ猫、水彩画風"",
              ""n"": 1,
              ""size"": ""16:9"",
              ""resolution"": ""2k""
          }";

          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);
      }
  }
  ```

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

  void main() async {
    final url = Uri.parse('https://api.apimart.ai/v1/images/generations');

    final payload = {
      'model': 'gpt-image-2',
      'prompt': '窓辺に座って夕日を見つめる茶トラ猫、水彩画風',
      'n': 1,
      'size': '16:9',
      'resolution': '2k'
    };

    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://api.apimart.ai/v1/images/generations"

  payload <- list(
    model = "gpt-image-2",
    prompt = "窓辺に座って夕日を見つめる茶トラ猫、水彩画風",
    n = 1,
    size = "16:9",
    resolution = "2k"
  )

  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}
  {
    "code": 200,
    "data": [
      {
        "status": "submitted",
        "task_id": "task_01KPQ7J7DWB7QZ3WCEK3YVPBRA"
      }
    ]
  }
  ```

  ```json 400 theme={null}
  {
    "error": {
      "code": 400,
      "message": "パラメータエラー：size が不正 / resolution が未対応 / ピクセル違反など",
      "type": "invalid_request_error"
    }
  }
  ```

  ```json 401 theme={null}
  {
    "error": {
      "code": 401,
      "message": "認証に失敗しました。API キーをご確認ください",
      "type": "authentication_error"
    }
  }
  ```

  ```json 402 theme={null}
  {
    "error": {
      "code": 402,
      "message": "アカウント残高が不足しています。チャージ後に再試行してください",
      "type": "payment_required"
    }
  }
  ```

  ```json 429 theme={null}
  {
    "error": {
      "code": 429,
      "message": "リクエストが多すぎます。しばらくしてから再試行してください",
      "type": "rate_limit_error"
    }
  }
  ```

  ```json 500 theme={null}
  {
    "error": {
      "code": 500,
      "message": "build_request_failed: invalid size: 3:5, allowed: 1:1 / 16:9 / 9:16 / 4:3 / 3:4 / 3:2 / 2:3 / 5:4 / 4:5 / 2:1 / 1:2 / 3:1 / 1:3 / 21:9 / 9:21",
      "type": "server_error"
    }
  }
  ```

  ```json 503 theme={null}
  {
    "error": {
      "code": 503,
      "message": "上流が一時的に利用できません。しばらくしてから再試行してください",
      "type": "service_unavailable"
    }
  }
  ```
</ResponseExample>

## Authorizations

<ParamField header="Authorization" type="string" required>
  すべてのエンドポイントは Bearer Token による認証が必要です

  API キーの取得：

  [API キー管理ページ](https://apimart.ai/keys) にアクセスして API キーを取得してください

  使用時はリクエストヘッダーに以下を追加：

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

## Body

<ParamField body="model" type="string" default="gpt-image-2" required>
  画像生成モデル名

  `gpt-image-2` に固定（エイリアス `gpt-image-2-ext` に対応）

  <Note>
    旧バージョンの呼び出しとの互換性のため、エイリアス `gpt-image-2-ext`（`gpt-image-2` に対応）は引き続き正常に使用できます。
  </Note>
</ParamField>

<ParamField body="prompt" type="string" required>
  画像生成のテキスト記述

  * 日本語・英語・中国語をサポート、詳細な記述を推奨
  * 送信前にプラットフォームのセンシティブワード / セーフティレビューを通過します。違反内容は即座にエラーを返します
</ParamField>

<ParamField body="n" type="integer" default="1">
  生成する画像の枚数

  範囲：`1 - 10`

  <Warning>
    必ず数値（例：`1`）を入力してください。引用符で囲まないでください
  </Warning>
</ParamField>

<ParamField body="size" type="string" default="1:1">
  画像生成の比率

  以下の比率をサポート、`auto` を渡すとサーバー側で適切な比率を自動選択します：

  | size   | タイプ |
  | ------ | --- |
  | `auto` | 自動  |
  | `1:1`  | 正方形 |
  | `3:2`  | 横   |
  | `2:3`  | 縦   |
  | `4:3`  | 横   |
  | `3:4`  | 縦   |
  | `5:4`  | 横   |
  | `4:5`  | 縦   |
  | `16:9` | 横   |
  | `9:16` | 縦   |
  | `2:1`  | 横   |
  | `1:2`  | 縦   |
  | `3:1`  | 横   |
  | `1:3`  | 縦   |
  | `21:9` | 横   |
  | `9:21` | 縦   |

  `1881x836` / `887x1774` のようなピクセルサイズも直接指定できます。

  <Warning>
    `size` に `auto` を指定した場合、デフォルトの比率は `1:1` です。
  </Warning>
</ParamField>

<ParamField body="resolution" type="string" default="1k">
  出力解像度の段階

  選択肢：`1k` / `2k` / `4k`

  `size × resolution` → 実際のピクセル対応：

  | size   | `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** |
  | `3:1`  | 1881×836 / 1536×512   | 3072×1024 | **3840×1280** |
  | `1:3`  | 887×1774 / 512×1536   | 1024×3072 | **1280×3840** |
  | `21:9` | 2016×864 / 1915×821   | 2688×1152 | **3840×1648** |
  | `9:21` | 864×2016 / 821×1915   | 1152×2688 | **1648×3840** |

  <Warning>
    4K は上記 15 種類の比率をサポートします。表内のピクセルサイズを `size` で直接指定することもできます。
  </Warning>
</ParamField>

<ParamField body="image_urls" type="array">
  参照画像配列（OpenAI 標準フィールド）。渡すと画像から画像モードに切り替わります

  <Expandable title="詳細">
    * 参照画像は最大 16 枚。超過すると `image_urls exceeds max 16` が返ります
    * 1 枚あたり最大 20MB、合計上限 256MB
    * `画像 URL`（公開アクセス可能な安定したリンク）をサポート
    * `base64 data URI`（例：`data:image/png;base64,...`）をサポート
    * 同じ配列内で URL と base64 を混在可能、サーバー側で処理します
    * `size` を渡さない場合、出力解像度 = 入力画像の解像度。`size` を渡すと指定サイズに強制
  </Expandable>
</ParamField>

<Note>
  その他の OpenAI 標準フィールド（`response_format`、`style` など）は現在サポートされておらず、無視されます。タスク結果は `url` のみを返します。base64 が必要な場合はご自身でダウンロードして変換してください。
</Note>

<ParamField body="official_fallback" type="boolean" default="false">
  公式チャネルをフォールバックとして使用するかどうか

  * `false`：使用しない（デフォルト）
  * `true`：公式チャネルを使用
</ParamField>

## 使用シナリオ例

**テキストから画像（最小リクエスト）**

```json theme={null}
{
  "model": "gpt-image-2",
  "prompt": "窓辺に座って夕日を見つめる茶トラ猫、水彩画風"
}
```

**テキストから画像（比率指定 + 2K）**

```json theme={null}
{
  "model": "gpt-image-2",
  "prompt": "a corgi astronaut on the moon, cinematic, 8k",
  "size": "16:9",
  "resolution": "2k"
}
```

**テキストから画像（4K 出力）**

```json theme={null}
{
  "model": "gpt-image-2",
  "prompt": "星空の下の古城",
  "size": "16:9",
  "resolution": "4k"
}
```

**テキストから画像（複数枚）**

```json theme={null}
{
  "model": "gpt-image-2",
  "prompt": "星空の下の古城",
  "size": "16:9",
  "resolution": "4k",
  "n": 2
}
```

**画像から画像（参照 = URL）**

```json theme={null}
{
  "model": "gpt-image-2",
  "prompt": "この写真を水彩画風に変換",
  "image_urls": [
    "https://example.com/photo.jpg"
  ]
}
```

**画像から画像（参照 = base64）**

```json theme={null}
{
  "model": "gpt-image-2",
  "prompt": "この写真を水彩画風に変換",
  "image_urls": [
    "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..."
  ]
}
```

**画像から画像（複数参照融合、URL + base64 混在）**

```json theme={null}
{
  "model": "gpt-image-2",
  "prompt": "この 2 枚の写真を 1 枚のポスターに融合",
  "size": "4:3",
  "resolution": "2k",
  "image_urls": [
    "https://example.com/photo-a.jpg",
    "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..."
  ]
}
```

## Response

<ResponseField name="code" type="integer">
  レスポンスステータスコード
</ResponseField>

<ResponseField name="data" type="array">
  レスポンスデータ配列

  <Expandable title="プロパティ">
    <ResponseField name="status" type="string">
      タスクステータス

      * `submitted` - 提出済み
    </ResponseField>

    <ResponseField name="task_id" type="string">
      タスクの一意識別子。後続の結果クエリに使用します
    </ResponseField>
  </Expandable>
</ResponseField>

## タスク結果のクエリ

提出成功後に `task_id` が返されます。`GET /v1/tasks/{task_id}` でタスク状態をポーリングしてください。詳細は [タスククエリ API](/ja/api-reference/tasks/status) を参照。

### 成功レスポンス例

```json theme={null}
{
  "code": 200,
  "data": {
    "id": "task_01KPQ7J7DWB7QZ3WCEK3YVPBRA",
    "status": "completed",
    "progress": 100,
    "created": 1776748674,
    "completed": 1776748726,
    "actual_time": 52,
    "cost": 0.05279,
    "credits_cost": 0.5279,
    "estimated_time": 100,
    "result": {
      "images": [
        {
          "url": [
            "https://upload.apimart.ai/f/image/xxxxxxxx-gpt_image_2_task_xxx_0.png"
          ],
          "expires_at": 1776835126
        }
      ]
    }
  }
}
```

画像の取得：`data.result.images[0].url[0]`

### タスクステータス

| ステータス        | 意味                      |
| ------------ | ----------------------- |
| `submitted`  | 提出済み                    |
| `processing` | 上流で処理中                  |
| `completed`  | 成功、`result.images` 利用可能 |
| `failed`     | 失敗、`error.message` を確認  |
