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

# Seedream-5.0-Flash 画像生成

>  - 非同期処理モード、後続のクエリ用にタスク ID を返します
- テキストから画像、単一画像から画像、複数参照画像から画像（最大 10 枚の参照画像）をサポート
- 1K / 1.5K / 2K 解像度段階、または `size` で正確なピクセルを指定
- 単一画像モデル：リクエストごとに 1 枚のみ；PNG / JPEG 出力
- 生成された画像リンクは72時間有効です。お早めに保存してください 

<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": "seedream-5-0-flash",
      "prompt": "サイバーパンク風の街の夜景、濡れた路面に反射するネオンライト",
      "size": "16:9",
      "resolution": "2K"
    }'
  ```

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

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

  payload = {
      "model": "seedream-5-0-flash",
      "prompt": "サイバーパンク風の街の夜景、濡れた路面に反射するネオンライト",
      "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: "seedream-5-0-flash",
    prompt: "サイバーパンク風の街の夜景、濡れた路面に反射するネオンライト",
    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":      "seedream-5-0-flash",
          "prompt":     "サイバーパンク風の街の夜景、濡れた路面に反射するネオンライト",
          "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": "seedream-5-0-flash",
            "prompt": "サイバーパンク風の街の夜景、濡れた路面に反射するネオンライト",
            "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" => "seedream-5-0-flash",
      "prompt" => "サイバーパンク風の街の夜景、濡れた路面に反射するネオンライト",
      "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: "seedream-5-0-flash",
    prompt: "サイバーパンク風の街の夜景、濡れた路面に反射するネオンライト",
    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": "seedream-5-0-flash",
      "prompt": "サイバーパンク風の街の夜景、濡れた路面に反射するネオンライト",
      "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"": ""seedream-5-0-flash"",
              ""prompt"": ""サイバーパンク風の街の夜景、濡れた路面に反射するネオンライト"",
              ""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);
      }
  }
  ```

  ```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://api.apimart.ai/v1/images/generations";
          const char *payload = "{"
              "\"model\":\"seedream-5-0-flash\","
              "\"prompt\":\"サイバーパンク風の街の夜景、濡れた路面に反射するネオンライト\","
              "\"size\":\"16:9\","
              "\"resolution\":\"2K\""
          "}";

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

          NSDictionary *payload = @{
              @"model": @"seedream-5-0-flash",
              @"prompt": @"サイバーパンク風の街の夜景、濡れた路面に反射するネオンライト",
              @"size": @"16:9",
              @"resolution": @"2K"
          };

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

  let payload = {|{
    "model": "seedream-5-0-flash",
    "prompt": "サイバーパンク風の街の夜景、濡れた路面に反射するネオンライト",
    "size": "16:9",
    "resolution": "2K"
  }|}

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

    final payload = {
      'model': 'seedream-5-0-flash',
      'prompt': 'サイバーパンク風の街の夜景、濡れた路面に反射するネオンライト',
      '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 = "seedream-5-0-flash",
    prompt = "サイバーパンク風の街の夜景、濡れた路面に反射するネオンライト",
    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_01K8SGYNNNVBQTXNR4MM964S7K"
      }
    ]
  }
  ```

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

## 認証

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

  APIキーの取得：

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

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

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

<Info>
  **単一画像モデル**：`seedream-5-0-flash` はリクエスト1回につき1枚のみ生成します（レイヤー分解を除く）。次のパラメータは**拒否**されます（HTTP 400、タスク作成なし、課金なし）：

  * `n > 1`
  * `sequential_image_generation`（グループ生成は非対応）
  * `stream`（ストリーミングは非対応）
  * `tools`（Web検索は非対応）
  * `image_urls` が 10 枚を超える
</Info>

<CardGroup cols={2}>
  <Card title="インタラクティブ編集" icon="crosshairs">
    プロンプトで `<point>` / `<bbox>` 座標を使用するか、手書き注釈付き画像をアップロードして、編集位置を正確に指定します。

    * 点座標：`<point>x y</point>`（1 点を指定し、影響範囲はモデルが判断します）
    * バウンディングボックス座標：`<bbox>x1 y1 x2 y2</bbox>`（左上と右下の座標を指定し、編集領域のサイズを正確に制御します）
  </Card>

  <Card title="レイヤー分解" icon="layer-group">
    1枚の画像をベース画像と最大16個の透過PNGレイヤーに分解し、位置と重なり順の情報を返します。
  </Card>
</CardGroup>

## Body

<ParamField body="model" type="string" default="seedream-5-0-flash" required>
  画像生成モデル名

  * `seedream-5-0-flash`（推奨）
  * 互換エイリアス：`seedream-5.0-pro`
</ParamField>

<ParamField body="nsfw_check" type="boolean" default="false">
  画像タスクを送信する前にコンテンツモデレーションを実行するかどうかを指定します。

  * `true`：`omni-moderation-latest` でプロンプトと入力画像を審査
  * `false` または省略：審査リクエストを行わず、審査コストや遅延を追加しない（デフォルト）
</ParamField>

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

  `layer_decomposition: true` の場合は省略可能です。省略すると、モデルが画像内の主要要素を自動識別して分離します。

  中国語と英語に加え、ロシア語、アラビア語、フィリピン語、タイ語、トルコ語、韓国語、マレー語、スペイン語、ポルトガル語、インドネシア語、フランス語、ドイツ語、ベトナム語、日本語のネイティブ文字生成に対応します。

  > **ヒント：** 600 英単語以内に抑えてください。説明が長すぎるとディテールが失われる可能性があります。
</ParamField>

<ParamField body="resolution" type="string" default="1K">
  解像度ティア（小文字も可）。API Martの拡張フィールドで、ティアを `size` に直接指定する場合と同等です。

  * `1K`（デフォルト）
  * `1.5K`（1K と同価格で画質が良い — 特段の理由がなければ 1.5K を推奨）
  * `2K`

  3K / 4K など未対応の段階は 400 を返します。

  ティア形式の `size` と `resolution` を同時に指定した場合は、`size` が優先されます。

  <Warning>
    `size` が**正確なピクセル値**（例：`2048x1024`）の場合、本フィールドは**無視**され、寸法は `size` のみで決まります。
  </Warning>
</ParamField>

<ParamField body="size" type="string" default="auto">
  ティアキーワード、アスペクト比、`auto`、または**正確なピクセル寸法**を指定します。

  ### 形式 ①：解像度ティア（推奨）

  ティアは `size` に直接記述するか、API Mart拡張フィールド `resolution` で指定できます：

  ```json theme={null}
  { "size": "2K" }
  ```

  ```json theme={null}
  { "resolution": "2K" }
  ```

  2つの形式は同等です。ティアだけを指定する場合は、プロンプトで用途（例：「縦長ポスター」「横長カバー」）を説明し、モデルにアスペクト比を選択させます。

  ### 形式 ②：ティア + アスペクト比

  `resolution` と併用。対応比率：

  * `1:1`、`4:3`、`3:4`、`16:9`、`9:16`、`3:2`、`2:3`、`2:1`、`1:2`、`21:9`
  * `16x9` 形式の `x` 区切りも可
  * `2x1` は `2:1`、`1x2` は `1:2` と同じです。`x` は小文字で、空白は使用できません。
  * `auto`（デフォルト）：解像度段階のみ適用；最終比率は prompt / 参照画像から決定

  リスト外の比率（例：`9:21`）は 400 — **1:1 への暗黙のフォールバックなし**。

  **段階 × 比率 → 出力ピクセル：**

  | 解像度      | 1:1       | 4:3       | 3:4       | 16:9      | 9:16      | 3:2       | 2:3       | 2:1       | 1:2       | 21:9      |
  | -------- | --------- | --------- | --------- | --------- | --------- | --------- | --------- | --------- | --------- | --------- |
  | **1K**   | 1024×1024 | 1152×864  | 864×1152  | 1312×736  | 736×1312  | 1248×832  | 832×1248  | 1440×720  | 720×1440  | 1568×672  |
  | **1.5K** | 1536×1536 | 1792×1344 | 1344×1792 | 2048×1152 | 1152×2048 | 1872×1248 | 1248×1872 | 2176×1088 | 1088×2176 | 2352×1008 |
  | **2K**   | 2048×2048 | 2304×1728 | 1728×2304 | 2560×1440 | 1440×2560 | 2496×1664 | 1664×2496 | 2880×1440 | 1440×2880 | 3024×1296 |

  ```json theme={null}
  { "resolution": "2K", "size": "2:1" }
  ```

  ### 形式 ③：正確なピクセル

  `size` が `widthxheight` の場合、ピクセルがそのまま使われ `resolution` は適用されません。`2048X1024` / `2048×1024` も可。

  | 制約             | 範囲                                                      |
  | -------------- | ------------------------------------------------------- |
  | 総ピクセル数（幅 × 高さ） | `[921600, 4624220]`（約 `1280×720` \~ `2048×2048×1.1025`） |
  | アスペクト比（幅 / 高さ） | `[1/16, 16]`                                            |

  <Warning>
    制限は幅と高さの**積**に対するもので、各辺単独ではありません。例：`512×512` は小さすぎ（400）；`2048×1024` は有効。
  </Warning>
</ParamField>

<ParamField body="background" type="string" default="opaque">
  出力背景モード：

  * `opaque`: 不透明背景（デフォルト）
  * `transparent`: 透過背景

  `transparent` は、アルファチャネルを持つ1枚の入力画像を使用する画像から画像へのリクエストでのみ利用でき、`output_format: "png"` も必要です。
</ParamField>

<ParamField body="layer_decomposition" type="boolean" default="false">
  画像をレイヤーに分解するかどうか。有効にすると、1枚のベース画像と最大16個のアルファチャネル付きPNGレイヤーを返します。

  PNGまたはJPEG画像を1枚だけ指定します。総ピクセル数は `[262144, 36000000]`、サイズは30 MB以下である必要があります。`size` は `1K`、`1.5K`、`2K`、`auto` のみを受け付け、デフォルトは `auto` です。`output_format` はベース画像の形式だけを制御し、分解レイヤーは常にPNGです。
</ParamField>

<ParamField body="optimize_prompt_options" type="object" default={'{"mode":"standard"}'}>
  プロンプト最適化モード：

  * `standard`: 高品質な標準モード（デフォルト）

  フラット形式 `"optimize_prompt_options.mode": "standard"` も使用できます。
</ParamField>

<ParamField body="n" type="integer" default="1">
  生成する画像数。`1` のみ対応します。グループ画像生成には `seedream-5-0-lite` を使用してください。
</ParamField>

<ParamField body="image_urls" type="array">
  参照画像 URL リスト。単一 / 複数参照の image-to-image 用、**最大 10 枚**

  2 つの形式：

  **1. 公開 URL**

  * `http://` または `https://`
  * 例：`https://example.com/image.jpg`

  **2. Base64（Data URI）**

  * 形式：`data:image/<format>;base64,<data>` — `<format>` は**小文字必須**
  * 例：`data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABg...`

  **画像ごとの制限：**

  * 形式：jpeg / png / webp / bmp / tiff / gif / heic / heif
  * アスペクト比（w/h）：`[1/16, 16]`
  * 各辺 > 14 px
  * サイズ ≤ 30 MB
  * 総ピクセル ≤ `6000×6000`（36,000,000）

  > **課金：** 最初の参照画像は無料；追加の各画像に固定の追加料金。
</ParamField>

<ParamField body="output_format" type="string" default="jpeg">
  出力画像フォーマット

  * `jpeg`（デフォルト）
  * `png`

  > **互換：** `response_format` は `output_format` と同等；その他の値は `jpeg` として扱われます。
</ParamField>

<ParamField body="watermark" type="boolean" default="false">
  右下に "AI generated" ウォーターマークを付けるか

  * `true`：ウォーターマークあり
  * `false`：なし（デフォルト）
</ParamField>

## リクエスト例

### テキストから画像（段階 + 比率）

```json theme={null}
{
  "model": "seedream-5-0-flash",
  "prompt": "サイバーパンクの都市夜景、濡れた路面に反射するネオン",
  "resolution": "2K",
  "size": "2:1",
  "output_format": "png"
}
```

### テキストから画像（正確なピクセル）

```json theme={null}
{
  "model": "seedream-5-0-flash",
  "prompt": "ミニマルな EC ヒーロー画像、白背景、商品中央",
  "size": "1600x1600"
}
```

### 複数参照

```json theme={null}
{
  "model": "seedream-5-0-flash",
  "prompt": "画像 1 の服装を画像 2 の服装に置き換える",
  "image_urls": [
    "https://example.com/person.jpg",
    "https://example.com/dress.jpg"
  ],
  "resolution": "2K",
  "size": "auto"
}
```

### 推奨：1.5K 同価格で高画質

```json theme={null}
{
  "model": "seedream-5-0-flash",
  "prompt": "窓辺の午後の日差しを浴びるかわいいオレンジ色の猫、シネマティック",
  "resolution": "1.5K",
  "size": "16:9"
}
```

### レイヤー分解

```json theme={null}
{
  "model": "seedream-5-0-flash",
  "image_urls": ["https://example.com/poster.png"],
  "layer_decomposition": true,
  "size": "2K"
}
```

`0–1000` に正規化した `<bbox>` 座標で、抽出する要素を正確に指定できます：

```json theme={null}
{
  "model": "seedream-5-0-flash",
  "prompt": "画像を正確なレイヤーに分離する。テキストの座標は <bbox>180 64 812 198</bbox>、オウムの座標は <bbox>347 305 642 997</bbox>。",
  "image_urls": ["https://example.com/poster.png"],
  "layer_decomposition": true
}
```

### インタラクティブ編集

画像内の手書き注釈を自然言語で説明します：

```json theme={null}
{
  "model": "seedream-5-0-flash",
  "prompt": "スケッチに従って画像を編集する。左下のマーク領域に雑誌の山を、右のマーク領域にコーヒーカップを追加する。スケッチ線をすべて削除し、構図を保つ。",
  "image_urls": ["https://example.com/sketch.png"],
  "size": "2K",
  "output_format": "png"
}
```

または `<point>` / `<bbox>` で位置を正確に指定します：

```json theme={null}
{
  "model": "seedream-5-0-flash",
  "prompt": "画像1の <bbox>179 283 796 986</bbox> にある被写体を、画像2の <bbox>118 331 933 871</bbox> の位置に配置する。",
  "image_urls": [
    "https://example.com/a.png",
    "https://example.com/b.png"
  ]
}
```

### アルファチャネル編集

```json theme={null}
{
  "model": "seedream-5-0-flash",
  "prompt": "透過背景を保ったままオウムをクジャクに変更する",
  "image_urls": ["https://cdn.example.com/images/layer.png"],
  "background": "transparent",
  "output_format": "png",
  "size": "2K"
}
```

## 完全な例：タスクを送信して画像を取得

次のスクリプトは、非同期タスクの送信、ステータスのポーリング、失敗状態の処理、最終画像URLの取得までのフローを示します。実行前に `YOUR_API_KEY` を置き換えてください。

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

API_KEY = "YOUR_API_KEY"
BASE_URL = "https://api.apimart.ai"
headers = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json",
}

# 1. 生成タスクを送信
create_response = requests.post(
    f"{BASE_URL}/v1/images/generations",
    headers=headers,
    json={
        "model": "seedream-5-0-flash",
        "prompt": "水墨画風の江南の水郷、薄い朝霧",
        "resolution": "1.5K",
        "size": "16:9",
        "output_format": "png",
    },
    timeout=30,
)
create_response.raise_for_status()
task_id = create_response.json()["data"][0]["task_id"]
print(f"タスクを送信しました： {task_id}")

# 2. タスクステータスをポーリング
while True:
    task_response = requests.get(
        f"{BASE_URL}/v1/tasks/{task_id}",
        headers=headers,
        timeout=30,
    )
    task_response.raise_for_status()
    task = task_response.json()
    status = task["status"]
    print(f"ステータス：{status}、進捗：{task.get('progress', 0)}%")

    if status == "success":
        image = task["result"]["images"][0]
        print("画像URL：", image["url"][0])
        print("画像サイズ：", image["sizes"][0])
        print("画像形式：", image["output_formats"][0])
        break

    if status in {"failed", "cancelled"}:
        raise RuntimeError(task.get("error", f"タスク{status}"))

    time.sleep(5)
```

成功時、タスク照会エンドポイントは次を返します：

```json theme={null}
{
  "id": "task_01JFXYZ123456789ABCDEF",
  "status": "success",
  "progress": 100,
  "cost": 0.045,
  "result": {
    "images": [
      {
        "url": ["https://cdn.example.com/images/image_task_xxx_0.png"],
        "sizes": ["2048x1152"],
        "output_formats": ["png"],
        "expires_at": 1784696685
      }
    ]
  }
}
```

<Note>
  返却画像はプラットフォーム管理のストレージにミラーされます。それでも自社システムへ速やかにダウンロードして永続保存し、結果URLを永久ストレージとして扱わないでください。
</Note>

## 完全なcURLシナリオ

### 複数画像の合成（参照画像は最大10枚）

```bash theme={null}
curl -X POST "https://api.apimart.ai/v1/images/generations" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "seedream-5-0-flash",
    "prompt": "画像1の人物を画像2のシーンに配置し、照明を黄昏時に統一する",
    "image_urls": [
      "https://example.com/person.jpg",
      "https://example.com/scene.jpg"
    ],
    "resolution": "1.5K",
    "size": "16:9",
    "output_format": "png"
  }'
```

### 正確なピクセル、プロンプト最適化、透かし

```bash theme={null}
curl -X POST "https://api.apimart.ai/v1/images/generations" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "seedream-5-0-flash",
    "prompt": "雨に濡れた道路にネオンが反射するサイバーパンク都市のスカイライン",
    "size": "2048x1024",
    "optimize_prompt_options": { "mode": "standard" },
    "watermark": true
  }'
```

### 透過レイヤーを分解して個別に編集

まず、元画像を分解します：

```bash theme={null}
curl -X POST "https://api.apimart.ai/v1/images/generations" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "seedream-5-0-flash",
    "image_urls": ["https://example.com/poster.png"],
    "layer_decomposition": true,
    "size": "2K"
  }'
```

次に、透過レイヤーのURLを取得し、個別に編集します：

```bash theme={null}
curl -X POST "https://api.apimart.ai/v1/images/generations" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "seedream-5-0-flash",
    "prompt": "画像内のオウムをクジャクに変更する",
    "image_urls": ["https://cdn.example.com/images/image_task_xxx_4.png"],
    "background": "transparent",
    "output_format": "png",
    "size": "2K"
  }'
```

## レイヤー分解レスポンスと復元

`url`、`sizes`、`output_formats`、`layers` 配列はインデックスごとに対応し、インデックス `0` は常にベース画像です：

```json theme={null}
{
  "result": {
    "images": [{
      "url": [
        "https://cdn.example.com/images/image_task_xxx_0.jpeg",
        "https://cdn.example.com/images/image_task_xxx_1.png",
        "https://cdn.example.com/images/image_task_xxx_2.png"
      ],
      "sizes": ["2048x2048", "1273x265", "492x98"],
      "output_formats": ["jpeg", "png", "png"],
      "layer_decomposition": true,
      "layers": [
        { "z_index": 0, "size": "2048x2048", "output_format": "jpeg" },
        {
          "z_index": 1,
          "size": "1273x265",
          "output_format": "png",
          "name": "タイトル文字",
          "description": "黄色の大きなセリフ体タイトル文字",
          "bounding_box": {
            "absolute": [383, 120, 1655, 384],
            "normalized": [187, 59, 808, 188]
          }
        },
        {
          "z_index": 2,
          "size": "492x98",
          "output_format": "png",
          "name": "左上のタグライン",
          "description": "白色の2行英語タグライン",
          "bounding_box": {
            "absolute": [140, 451, 631, 548],
            "normalized": [68, 220, 308, 268]
          }
        }
      ]
    }]
  }
}
```

`z_index` の昇順でレイヤーを合成します。絶対座標で出力ベース画像上に復元する場合：

```text theme={null}
x = left
y = top
w = right - left
h = bottom - top
```

任意の `W × H` キャンバス上に復元するには、正規化座標を使用します：

```text theme={null}
x = left / 1000 × W
y = top / 1000 × H
w = (right - left) / 1000 × W
h = (bottom - top) / 1000 × H
```

<Warning>
  レイヤー分解は画像ごとに課金されます。タスク送信時に最大17枚分を事前承認します。完了後は各出力を実際のピクセル数でティア判定して個別に精算し、過剰な事前承認額は自動返金します。残高は17枚分の事前承認をカバーする必要があり、`size: "auto"` は2Kティアで事前承認されます。
</Warning>

## 課金について

```
合計 = 出力単価 + 参照画像加算 × max(0, 参照枚数 − 1)
```

出力は**実際の総ピクセル数**で区分します（約 2.61M = 2,601,124）：

| 条件                                                                              | 単価              |
| ------------------------------------------------------------------------------- | --------------- |
| 総ピクセル ≤ 2.61M（1.5K 以下：`resolution` が `1K` / `1.5K` / 未指定、または正確ピクセル ≤ 2,601,124） | **\$0.045** / 枚 |
| 総ピクセル > 2.61M（1.5K 超：`resolution: "2K"`、または正確ピクセル > 2,601,124）                  | **\$0.09** / 枚  |

* **1.5K は 1K と同額**（いずれも \$0.045）。
* `size` が正確ピクセルのとき、課金は**実際の出力面積**で決まり、`resolution` は影響しません（例：`size: "2048x2048"` → \$0.09）。
* 参照画像の 1 枚目は無料、2 枚目以降は加算。
* タスク失敗時は自動で全額返金。

### レイヤー分解の事前承認と精算

タスク送信時に最終的なレイヤー数と寸法が不明なため、事前承認はリクエストに基づく保守的なルールで行われます：

* 正確なピクセル：指定したピクセル面積でティア判定。
* `1K` / `1.5K`：1Kティアで事前承認。
* `2K`：2Kティアで事前承認。
* `auto`：最大2Kで出力できるため、2Kティアで事前承認。

完了後、ベース画像と実際の各レイヤーを実ピクセル面積で**個別にティア判定して合算**します。過剰な事前承認額は自動返金されます。レイヤーは通常ベース画像より大幅に小さいため、2Kティアで事前承認されたタスクでも、最終的にすべて1Kティアで精算される場合があります。

<Info>
  例：`1080×1080` の入力を10枚の画像に分解する場合、`17枚 × 2Kティア` で事前承認します。最終的10枚がすべち261万ピクセル以下なら、`10枚 × 1Kティア` で精算し、残額を自動返金します。
</Info>

## よくあるエラー

| ケース                     | 説明                                                             |
| ----------------------- | -------------------------------------------------------------- |
| 未対応の `resolution` 段階    | 例：3K / 4K → 400                                                |
| 非対応の `size` 値           | `1K` / `1.5K` / `2K` / `auto`、対応アスペクト比、有効なピクセル寸法のいずれでもない → 400 |
| 正確ピクセルの総数が範囲外           | `[921600, 4624220]` 内である必要                                     |
| 正確ピクセルの比率が範囲外           | `[1/16, 16]` 内である必要                                            |
| `n > 1` / グループ画像パラメータ   | 単一画像モデルにより拒否                                                   |
| 参照画像が10枚を超える            | Rejected                                                       |
| 画像なし、または複数画像でのレイヤー分解    | 画像を1枚だけ指定する必要があります                                             |
| 比率または正確なピクセルを使用したレイヤー分解 | `size` は `1K` / `1.5K` / `2K` / `auto` のみ対応                    |
| テキストから画像または複数入力で透過背景を使用 | アルファチャネル付き入力画像を1枚だけ指定する必要があります                                 |
| JPEGで透過背景を使用            | `output_format: "png"` を設定                                     |
| `stream` / `tools`      | このモデルは非対応。400を返します                                             |
| 無効なプロンプト最適化モード          | `standard` のみ対応                                                |

<Note>
  ⏱️ **生成に時間がかかります**：1Kは約90秒、2Kは約160秒（品質優先）。5〜10秒ごとに[タスクステータスを取得](/ja/api-reference/tasks/status)し、クライアントのタイムアウトを **5分** に設定してください。生成結果は速やかに保存してください。
</Note>

## レスポンス

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