> ## 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(1/1.5) 画像生成

>  - 非同期処理モード、タスクIDを返して後続のクエリに使用
- テキストから画像、画像から画像、インペインティングなど複数の生成モードに対応
- 透明背景、複数の出力形式、複数の品質レベルに対応
- 1回のリクエストで最大4枚生成、参照画像は最大15枚 

<RequestExample>
  ```bash cURL theme={null}
  curl --request POST \
    --url https://api.apimart.ai/v1/images/generations \
    --header 'Authorization: Bearer <token>' \
    --header 'Content-Type: application/json' \
    --data '{
      "model": "gpt-image-1-official",
      "prompt": "星空の下の古い城",
      "size": "1:1",
      "quality": "auto",
      "n": 1
    }'
  ```

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

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

  payload = {
      "model": "gpt-image-1-official",
      "prompt": "星空の下の古い城",
      "size": "1:1",
      "quality": "auto",
      "n": 1
  }

  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-1-official",
    prompt: "星空の下の古い城",
    size: "1:1",
    quality: "auto",
    n: 1,
  };

  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-1-official",
          "prompt":  "星空の下の古い城",
          "size":    "1:1",
          "quality": "auto",
          "n":       1,
      }

      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-1-official",
            "prompt": "星空の下の古い城",
            "size": "1:1",
            "quality": "auto",
            "n": 1
          }
          """;

          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-1-official",
      "prompt" => "星空の下の古い城",
      "size" => "1:1",
      "quality" => "auto",
      "n" => 1
  ];

  $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-1-official",
    prompt: "星空の下の古い城",
    size: "1:1",
    quality: "auto",
    n: 1
  }

  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-1-official",
      "prompt": "星空の下の古い城",
      "size": "1:1",
      "quality": "auto",
      "n": 1
  ]

  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-1-official"",
              ""prompt"": ""星空の下の古い城"",
              ""size"": ""1:1"",
              ""quality"": ""auto"",
              ""n"": 1
          }";

          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-1-official',
      'prompt': '星空の下の古い城',
      'size': '1:1',
      'quality': 'auto',
      'n': 1,
    };

    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-1-official",
    prompt = "星空の下の古い城",
    size = "1:1",
    quality = "auto",
    n = 1
  )

  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_01KXXXXXXXXXXXXXXX"
      }
    ]
  }
  ```

  ```json 400 theme={null}
  {
    "error": {
      "code": 400,
      "message": "リクエストパラメータが無効です",
      "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 403 theme={null}
  {
    "error": {
      "code": 403,
      "message": "アクセスが禁止されています。このリソースへのアクセス権限がありません",
      "type": "permission_error"
    }
  }
  ```

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

  ```json 500 theme={null}
  {
    "error": {
      "code": 500,
      "message": "サーバー内部エラーです。しばらくしてから再度お試しください",
      "type": "server_error"
    }
  }
  ```

  ```json 502 theme={null}
  {
    "error": {
      "code": 502,
      "message": "ゲートウェイエラー、サーバーが一時的に利用できません",
      "type": "bad_gateway"
    }
  }
  ```
</ResponseExample>

## サポートモデル

| モデル名                     | 説明                  | モード               | 画像から画像 | 最大枚数 | 課金方式   |
| ------------------------ | ------------------- | ----------------- | ------ | ---- | ------ |
| `gpt-image-1-official`   | 安定性重視、汎用画像生成に最適     | テキストから画像 / 画像から画像 | 対応     | 4枚   | サイズ×品質 |
| `gpt-image-1.5-official` | 新バージョン、高品質・複雑な編集に最適 | テキストから画像 / 画像から画像 | 対応     | 4枚   | サイズ×品質 |

## Authorizations

<ParamField header="Authorization" type="string" required>
  すべてのAPIリクエストにはBearer Token認証が必要です

  APIキーの取得：

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

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

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

## Body

<ParamField body="model" type="string" required>
  モデル名

  * `gpt-image-1-official` - 安定性重視、汎用画像生成に最適
  * `gpt-image-1.5-official` - 新バージョン、高品質・複雑な編集に最適
</ParamField>

<ParamField body="prompt" type="string" required>
  画像生成のテキスト説明、中国語と英語に対応
</ParamField>

<ParamField body="size" type="string" default="1:1">
  アスペクト比

  対応する比率：

  * `1:1` - 正方形（デフォルト）
  * `3:2` - 横長
  * `2:3` - 縦長
</ParamField>

<ParamField body="n" type="integer" default="1">
  生成枚数

  範囲：1-4

  * 0以下の値は `1` として処理されます
  * 4を超える値は `4` として処理されます

  **⚠️ 注意：** 純粋な数値（例：`1`）を入力してください。引用符を付けるとエラーになります
</ParamField>

<ParamField body="quality" type="string" default="auto">
  画像品質

  * `auto` - 自動品質選択（デフォルト）
  * `low` - より高速、より経済的
  * `medium` - 品質とコストのバランス
  * `high` - より高品質、コスト増
</ParamField>

<ParamField body="background" type="string" default="auto">
  背景モード

  * `auto` - 自動背景（デフォルト）
  * `opaque` - 不透明背景
  * `transparent` - 透明背景、`png` 出力形式との併用推奨

  <Warning>
    `background: transparent` と `output_format: jpeg` は同時に使用できません
  </Warning>
</ParamField>

<ParamField body="moderation" type="string" default="auto">
  モデレーションレベル

  * `auto` - デフォルトのモデレーションレベル
  * `low` - より緩やかなモデレーション
</ParamField>

<ParamField body="output_format" type="string" default="png">
  出力形式

  * `png` - デフォルト形式、透明背景に最適
  * `jpeg` - ファイルサイズが小さい、一般的な画像出力に最適

  <Warning>
    `background: transparent` と `output_format: jpeg` は同時に使用できません
  </Warning>
</ParamField>

<ParamField body="output_compression" type="integer">
  出力圧縮レベル、範囲 0-100

  * `jpeg` でのみ使用推奨
  * `png` では設定不要
</ParamField>

<ParamField body="image_urls" type="array">
  参照画像のURL配列、指定すると画像から画像モードが有効になります

  <Expandable title="詳細説明">
    * 1枚で単一参照画像編集
    * 2-15枚で複数参照画像の融合編集
    * 15枚を超えるとサーバーに拒否されます
    * 公開アクセス可能な安定した画像URLが必要です
  </Expandable>

  **制限：** 最大15枚の参照画像
</ParamField>

<ParamField body="mask_url" type="string">
  マスク画像URL、インペインティング用

  * `image_urls` と併用する必要があります
  * 公式編集APIで一緒に送信されます

  <Warning>
    1、マスク画像をアップロードする前に、画像のAlphaチャンネルが「はい」であることを確認してください。

    2、マスク画像のサイズは最初の参考画像と一致する必要があります。
  </Warning>
</ParamField>

## サイズ対照表

アスペクト比を外部で使用し、システム内部で公式の実際のサイズに自動マッピングします。

| 比率    | 実際のサイズ    | 説明  |
| ----- | --------- | --- |
| `1:1` | 1024×1024 | 正方形 |
| `2:3` | 1024×1536 | 縦長  |
| `3:2` | 1536×1024 | 横長  |

## 使用例

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

```json theme={null}
{
  "model": "gpt-image-1-official",
  "prompt": "星空の下の古い城"
}
```

**テキストから画像（全パラメータ）**

```json theme={null}
{
  "model": "gpt-image-1-official",
  "prompt": "A flat icon of a glass bottle with no background",
  "size": "2:3",
  "quality": "high",
  "background": "transparent",
  "moderation": "low",
  "output_format": "png",
  "n": 1
}
```

**画像から画像（単一参照画像）**

```json theme={null}
{
  "model": "gpt-image-1.5-official",
  "prompt": "参照画像をイラスト風に変換し、メインの輪郭を保持する",
  "size": "1:1",
  "quality": "auto",
  "image_urls": [
    "https://your-cdn.com/input.png"
  ],
  "n": 1
}
```

**画像から画像（複数参照画像の融合）**

```json theme={null}
{
  "model": "gpt-image-1.5-official",
  "prompt": "2枚の参照画像をイラストポスターに融合し、メインの輪郭を保持する",
  "size": "1:1",
  "quality": "auto",
  "background": "transparent",
  "image_urls": [
    "https://your-cdn.com/input-a.png",
    "https://your-cdn.com/input-b.png"
  ],
  "moderation": "low",
  "output_format": "png",
  "n": 1
}
```

**複数枚生成（n > 1）**

```json theme={null}
{
  "model": "gpt-image-1-official",
  "prompt": "Four minimalist poster variations of a red fox",
  "size": "1:1",
  "quality": "low",
  "output_format": "png",
  "n": 4
}
```

## 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>

## 注意事項

1. **非同期処理**：送信後に `task_id` が返されます。`/v1/tasks/{task_id}` をポーリングして結果を取得してください
2. **モデル選択**：汎用画像生成には `gpt-image-1-official` を優先使用。高品質編集や複雑な画像から画像には `gpt-image-1.5-official` を推奨
3. **画像URL要件**：画像から画像には、公開アクセス可能な安定した画像URLを使用してください
4. **課金ルール**：正常に生成された画像枚数で課金、失敗時は課金なし
