> ## 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 张参考图）
- 独有能力：坐标 / 手绘标记交互编辑、底图 + 最多 16 层的图层拆分
- 支持 1K / 1.5K / 2K 分辨率档位，或 `size` 直接指定精确像素
- 单图模型：每次仅生成 1 张；支持 PNG / JPEG 输出
- 输出图片镜像到平台自有存储并返回平台 URL 

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

## Authorizations

<ParamField header="Authorization" type="string" required>
  所有接口均需要使用Bearer Token进行认证

  获取 API Key：

  访问 [API Key 管理页面](https://apimart.ai/keys) 获取您的 API Key

  使用时在请求头中添加：

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

<Info>
  **单图模型**：`seedream-5-0-flash` 每次请求仅生成 1 张图像（图层拆分除外）。以下参数会**直接拒绝**（返回 400，不建任务、不扣费）：

  * `n > 1`
  * `sequential_image_generation`（不支持组图）
  * `stream`（不支持流式输出）
  * `tools`（不支持联网搜索）
  * `image_urls` 超过 10 张
</Info>

<CardGroup cols={2}>
  <Card title="交互编辑" icon="crosshairs">
    在提示词中使用 `<point>` / `<bbox>` 坐标，或上传带手绘标记的图片，精确指定编辑位置。

    * 点选坐标：`<point>x y</point>`（指定一个点，由模型判断影响范围）
    * 框选坐标：`<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">
  分辨率档位（兼容小写）。这是本站提供的扩展字段，等价于将档位直接写在 `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` 中，也可以使用本站扩展字段 `resolution`：

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

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

  上面两种写法等价。只指定档位时，可在 prompt 中描述“竖版海报”“横版封面”等用途，由模型决定宽高比。

  ### 写法 ②：档位 + 宽高比

  与 `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` 写成 `宽x高` 时**按像素输出**，`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 图层。

  开启时必须恰好传入 1 张 PNG 或 JPEG 图片，图片总像素须在 `[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 列表，用于单图 / 多参考图生图，**最多 10 张**

  支持两种格式：

  **1. 公网 URL**

  * `http://` 或 `https://` 可访问链接
  * 示例：`https://example.com/image.jpg`

  **2. Base64（Data URI）**

  * 格式：`data:image/<格式>;base64,<编码>`，`<格式>` **必须小写**
  * 示例：`data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABg...`

  **单张图片限制：**

  * 格式：jpeg / png / webp / bmp / tiff / gif / heic / heif
  * 宽高比（宽/高）：`[1/16, 16]`
  * 单边 > 14 px
  * 大小 ≤ 30 MB
  * 总像素 ≤ `6000×6000`（36,000,000）

  > **计费：** 第 1 张参考图免费，第 2 张起每张加收固定单价。
</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": "极简风格电商主图，白底，产品居中",
  "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"
}
```

## 完整示例：提交并获取图片

下面的脚本完整展示了提交异步任务、轮询任务状态、处理失败状态并读取最终图片地址的流程。复制前请替换 `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("图片地址：", 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": "白色两行英文标语",
          "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 张           | 拒绝                                                      |
| 图层拆分未传图或传入多张图        | 必须恰好传入 1 张图                                             |
| 图层拆分使用比例或精确像素        | `size` 仅支持 `1K` / `1.5K` / `2K` / `auto`                |
| 透明背景用于文生图或多图         | 必须恰好传入 1 张带透明通道的图片                                      |
| 透明背景与 JPEG 同时使用      | 设置 `output_format: "png"`                               |
| `stream` / `tools`   | 本模型不支持，直接返回 400                                         |
| 提示词优化模式非法            | 仅支持 `standard`                                          |

<Note>
  ⏱️ **生成较慢**：1K 约 90 秒、2K 约 160 秒（质量优先）。提交后每 5\~10 秒轮询一次 [获取任务状态](/cn/api-reference/tasks/status)，客户端超时建议 **5 分钟**。请及时保存生成结果。
</Note>

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