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

# 图像生成

> FocusAPI 图像生成接入指南：按 GPT 图像、Gemini/Imagen、Qwen/豆包等热门模型分别说明 curl、Python SDK、模型版本参数、可选值、多轮创作和特殊参数。

图像能力没有文本对话那样统一的事实标准。不同厂商、不同模型版本的参数差异很大，所以本页按 **模型系列** 写接入方式：每个模型系列只放适合它的 curl 和 Python SDK。

<Warning>
  `model`、尺寸、质量、比例等参数以控制台 **模型广场** 实际展示为准。下面示例用于说明接入方式，复制到生产前请先核对模型版本。
</Warning>

## 快速选择

| 模型系列               | 适合场景                              | 推荐调用                                 |
| ------------------ | --------------------------------- | ------------------------------------ |
| GPT 图像模型           | 高质量通用图片、图像编辑、OpenAI 生态            | curl + OpenAI Python SDK             |
| Gemini / Imagen    | 多模态生态、Imagen 图片生成、Google GenAI 生态 | curl + Gemini GenAI Python SDK       |
| Qwen / 豆包 / 其他兼容模型 | 中文提示词、营销素材、垂直风格                   | 优先看模型广场；常见为 OpenAI 兼容或厂商原生 SDK       |
| 图像编辑               | 改图、局部修改、风格迁移、参考图重绘                | 独立能力，见 [图像编辑](/models/image-editing) |

## GPT 图像模型

适合已经在使用 OpenAI Images API 的项目。常见模型包括 `gpt-image-1`、`dall-e-3`、`dall-e-2`，以模型广场实际上架为准。

<CodeGroup>
  ```bash cURL theme={null}
  curl https://www.focusapi.cn/v1/images/generations \
    -H "Authorization: Bearer sk-your-api-key" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "gpt-image-1",
      "prompt": "一只赛博朋克风格的猫，蓝紫色灯光",
      "size": "1024x1024",
      "quality": "medium",
      "n": 1
    }'
  ```

  ```python OpenAI SDK theme={null}
  import base64
  from urllib.request import urlopen
  from openai import OpenAI

  client = OpenAI(
      base_url="https://www.focusapi.cn/v1",
      api_key="sk-your-api-key",
  )

  image = client.images.generate(
      model="gpt-image-1",
      prompt="一只赛博朋克风格的猫，蓝紫色灯光",
      size="1024x1024",
      quality="medium",
      n=1,
      response_format="b64_json",
  )

  item = image.data[0]
  save_path = "focusapi-image.png"

  if item.b64_json:
      # b64_json 是 base64 字符串，不是 bytes；写入前必须先 b64decode
      with open(save_path, "wb") as f:
          f.write(base64.b64decode(item.b64_json))
  elif item.url:
      with open(save_path, "wb") as f:
          f.write(urlopen(item.url).read())

  print(f"已保存: {save_path}")
  ```
</CodeGroup>

<Note>
  OpenAI Python SDK 返回的 `b64_json` 是 **str**，不要对它调用 `.decode()`。保存图片应使用 `base64.b64decode(b64_json)` 得到二进制后再 `wb` 写入。若返回 `url`，直接下载 URL 内容即可。
</Note>

### GPT 图像参数

<Tabs>
  <Tab title="gpt-image-1">
    | 参数                | 说明        | 可选值                                 |
    | ----------------- | --------- | ----------------------------------- |
    | `size`            | 图片尺寸      | `1024x1024`、`1024x1536`、`1536x1024` |
    | `quality`         | 图片质量/成本档位 | `auto`、`low`、`medium`、`high`        |
    | `n`               | 生成张数      | 通常从 `1` 开始；批量上限以模型广场为准              |
    | `response_format` | 返回格式      | `url`、`b64_json`，以模型支持为准            |
  </Tab>

  <Tab title="dall-e-3">
    | 参数                | 说明   | 可选值                                 |
    | ----------------- | ---- | ----------------------------------- |
    | `size`            | 图片尺寸 | `1024x1024`、`1024x1792`、`1792x1024` |
    | `quality`         | 图片质量 | `standard`、`hd`                     |
    | `style`           | 画面风格 | `vivid`、`natural`                   |
    | `n`               | 生成张数 | `1`                                 |
    | `response_format` | 返回格式 | `url`、`b64_json`，以模型支持为准            |
  </Tab>

  <Tab title="dall-e-2">
    | 参数                | 说明   | 可选值                             |
    | ----------------- | ---- | ------------------------------- |
    | `size`            | 图片尺寸 | `256x256`、`512x512`、`1024x1024` |
    | `n`               | 生成张数 | 以模型广场为准                         |
    | `response_format` | 返回格式 | `url`、`b64_json`，以模型支持为准        |
  </Tab>
</Tabs>

## Gemini / Imagen 图像模型

适合已经使用 Google GenAI SDK 的项目。图像能力分 **两条接入路径**，不要混用：

| 模型类型            | 典型模型 ID                                                                                  | 调用方式                                                |
| --------------- | ---------------------------------------------------------------------------------------- | --------------------------------------------------- |
| **Imagen**      | `imagen-4.0-generate-001`、`imagen-4.0-generate-preview-06-06` 等                          | `generate_images` / `:predict`                      |
| **Gemini 图片生成** | `gemini-3.1-flash-image-preview`、`gemini-2.5-flash-image`、`gemini-3-pro-image-preview` 等 | `generate_content` / Chat，并设置 `response_modalities` |

<Warning>
  `gemini-3.1-flash-image-preview` 等 Gemini 图片模型 **不能** 使用 `client.models.generate_images()`。那是 Imagen 专用接口，换模型名也不会生效。
</Warning>

### Imagen 文生图

<CodeGroup>
  ```bash cURL theme={null}
  curl https://www.focusapi.cn/v1beta/models/imagen-4.0-generate-preview-06-06:predict \
    -H "x-goog-api-key: sk-your-api-key" \
    -H "Content-Type: application/json" \
    -d '{
      "instances": [
        {
          "prompt": "一张极简蓝色云朵图标，白色背景"
        }
      ],
      "parameters": {
        "sampleCount": 1,
        "aspectRatio": "1:1",
        "imageSize": "2K"
      }
    }'
  ```

  ```python Imagen GenAI SDK theme={null}
  from google import genai
  from google.genai import types

  client = genai.Client(
      api_key="sk-your-api-key",
      http_options=types.HttpOptions(base_url="https://www.focusapi.cn"),
  )

  response = client.models.generate_images(
      model="imagen-4.0-generate-preview-06-06",
      prompt="一张极简蓝色云朵图标，白色背景",
      config=types.GenerateImagesConfig(
          number_of_images=1,
          aspect_ratio="1:1",
          image_size="2K",
      ),
  )

  for image in response.generated_images:
      image.image.save("focusapi-image.png")
  ```
</CodeGroup>

### Gemini 图片生成模型

以 `gemini-3.1-flash-image-preview` 为例，使用 `generate_content` 并开启图片输出：

<CodeGroup>
  ```bash cURL theme={null}
  curl https://www.focusapi.cn/v1beta/models/gemini-3.1-flash-image-preview:generateContent \
    -H "x-goog-api-key: sk-your-api-key" \
    -H "Content-Type: application/json" \
    -d '{
      "contents": [
        {
          "role": "user",
          "parts": [
            { "text": "一张极简蓝色云朵图标，白色背景" }
          ]
        }
      ],
      "generationConfig": {
        "responseModalities": ["TEXT", "IMAGE"],
        "imageConfig": {
          "aspectRatio": "1:1",
          "imageSize": "1K"
        }
      }
    }'
  ```

  ```python Gemini GenAI SDK theme={null}
  import base64
  import os
  import re
  from datetime import datetime

  from google import genai
  from google.genai import types

  client = genai.Client(
      api_key="sk-your-api-key",
      http_options=types.HttpOptions(base_url="https://www.focusapi.cn"),
  )

  response = client.models.generate_content(
      model="gemini-3.1-flash-image-preview",
      contents="一张极简蓝色云朵图标，白色背景",
      config=types.GenerateContentConfig(
          response_modalities=["IMAGE"],
          image_config=types.ImageConfig(
              aspect_ratio="1:1",
              image_size="1K",
          ),
      ),
  )

  os.makedirs("output", exist_ok=True)
  saved_files = []

  for i, part in enumerate(response.parts):
      # 1. 优先保存图片（不要先 print text，否则只有 text part 时会错过保存）
      image = part.as_image()
      if image:
          filename = f"output/generated_image_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{i}.png"
          image.save(filename)
          saved_files.append(filename)
          print(f"图片已保存到 {filename}")
          continue

      # 2. 兼容：部分网关会把图片塞进 text 的 markdown data URL
      if part.text:
          match = re.search(r"data:image/[^;]+;base64,([A-Za-z0-9+/=]+)", part.text)
          if match:
              filename = f"output/generated_image_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{i}.png"
              with open(filename, "wb") as f:
                  f.write(base64.b64decode(match.group(1)))
              saved_files.append(filename)
              print(f"图片已保存到 {filename}")
              continue
          if len(part.text) < 500:
              print(part.text)

  if not saved_files:
      raise RuntimeError("响应里没有图片，请确认 model、response_modalities 和 base_url 是否正确")
  ```
</CodeGroup>

<Note>
  安装依赖：`pip install google-genai pillow`。保存图片时 **先调用 `part.as_image()`**，不要先 `print(part.text)`。若打印内容是一长串 base64 或 `![image](data:image/...)`，说明图片在 `text` 里，需用正则提取后 `base64.b64decode` 保存。生图建议 `response_modalities=["IMAGE"]`，减少纯文本 part 干扰。
</Note>

### Gemini / Imagen 参数

<Tabs>
  <Tab title="Imagen 4">
    | 参数                       | 说明                      | 可选值                             |
    | ------------------------ | ----------------------- | ------------------------------- |
    | `parameters.aspectRatio` | Gemini 原生 curl 的画幅比例    | `1:1`、`3:2`、`2:3`、`9:16`、`16:9` |
    | `parameters.imageSize`   | Gemini 原生 curl 的输出分辨率档位 | `1K`、`2K`                       |
    | `parameters.sampleCount` | Gemini 原生 curl 的生成张数    | 从 `1` 开始，最大值以模型广场为准             |
    | `aspect_ratio`           | GenAI SDK 的画幅比例         | `1:1`、`3:2`、`2:3`、`9:16`、`16:9` |
    | `image_size`             | GenAI SDK 的输出分辨率档位      | `1K`、`2K`                       |
    | `number_of_images`       | GenAI SDK 的生成张数         | 从 `1` 开始，最大值以模型广场为准             |
  </Tab>

  <Tab title="Imagen 3">
    | 参数                       | 说明                   | 可选值                             |
    | ------------------------ | -------------------- | ------------------------------- |
    | `parameters.aspectRatio` | Gemini 原生 curl 的画幅比例 | `1:1`、`3:2`、`2:3`、`9:16`、`16:9` |
    | `parameters.sampleCount` | Gemini 原生 curl 的生成张数 | 从 `1` 开始，最大值以模型广场为准             |
    | `aspect_ratio`           | GenAI SDK 的画幅比例      | `1:1`、`3:2`、`2:3`、`9:16`、`16:9` |
    | `number_of_images`       | GenAI SDK 的生成张数      | 从 `1` 开始，最大值以模型广场为准             |
  </Tab>

  <Tab title="Gemini 图片生成">
    | 参数                                            | 说明                                     | 可选值                             |
    | --------------------------------------------- | -------------------------------------- | ------------------------------- |
    | `response_modalities`                         | GenAI SDK / 原生 curl 必须开启图片输出           | `["TEXT", "IMAGE"]`             |
    | `image_config.aspect_ratio`                   | GenAI SDK 画幅比例                         | `1:1`、`3:2`、`2:3`、`9:16`、`16:9` |
    | `image_config.image_size`                     | GenAI SDK 分辨率档位                        | `1K`、`2K`                       |
    | `extra_body.google.image_config.aspect_ratio` | OpenAI 兼容 Chat Completions 生成图片时的比例参数  | `1:1`、`3:2`、`2:3`、`9:16`、`16:9` |
    | `extra_body.google.image_config.image_size`   | OpenAI 兼容 Chat Completions 生成图片时的分辨率档位 | `1K`、`2K`                       |
  </Tab>
</Tabs>

### Gemini 特殊参数

| 模型版本           | 参数                                            | 说明                                        | 可选值                             |
| -------------- | --------------------------------------------- | ----------------------------------------- | ------------------------------- |
| Gemini 多模态图片生成 | `extra_body.google.image_config.aspect_ratio` | 使用 OpenAI 兼容 Chat Completions 生成图片时的比例参数  | `1:1`、`3:2`、`2:3`、`9:16`、`16:9` |
| Gemini 多模态图片生成 | `extra_body.google.image_config.image_size`   | 使用 OpenAI 兼容 Chat Completions 生成图片时的分辨率档位 | `1K`、`2K`                       |

### 多轮图像创作

OpenAI 有两条生图路径，不要混用：

| 场景        | 官方接口                                                                   | 特点                                                               |
| --------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------- |
| 单张生成/单次编辑 | `client.images.generate` / `client.images.edit`                        | `model` 填 **`gpt-image-1`** 等图像模型                                |
| 多轮对话式改图   | `client.responses.create` + **`tools=[{"type": "image_generation"}]`** | `model` 填 **`gpt-4.1-mini`** 等支持该工具的主模型；实际画图由内置 `gpt-image-*` 完成 |

<Note>
  **为什么多轮要用 `tools`？** 这是 OpenAI Responses API 的官方设计：图片生成是 **hosted built-in tool**（平台托管的内置工具），不是你自己实现的 function。`gpt-4.1-mini` 负责理解意图并决定是否调用；真正画图在 tool 内完成。内置 tool 可在 `tools` 数组里指定底层图像模型（如 `model: "gpt-image-1"`），但不能换成任意非 OpenAI 图像模型——若模型广场没有对应 `gpt-image-*`，应改用 `client.images.generate(model="你上架的模型")` 或自定义 function 由你的服务转发。每一轮都要重新传 `tools`（不会自动继承）。
</Note>

<CodeGroup>
  ```python OpenAI Responses theme={null}
  import base64
  import os
  from openai import OpenAI

  client = OpenAI(
      base_url="https://www.focusapi.cn/v1",
      api_key="sk-your-api-key",
  )

  def save_image_from_response(response, save_path):
      for item in response.output:
          if item.type == "image_generation_call" and item.result:
              os.makedirs(os.path.dirname(save_path) or ".", exist_ok=True)
              with open(save_path, "wb") as f:
                  f.write(base64.b64decode(item.result))
              print(f"图片已保存到 {save_path}")
              return True
      return False

  first = client.responses.create(
      model="gpt-4.1-mini",
      input="生成一张极简蓝色云朵图标，白色背景，适合作为 App 图标。",
      tools=[{
          "type": "image_generation",
          "model": "gpt-image-1",       # 指定内置 tool 使用的图像模型（以模型广场为准）
          "size": "1024x1024",
          "quality": "medium",
      }],
  )

  save_image_from_response(first, "output/cloud-v1.png")

  second = client.responses.create(
      model="gpt-4.1-mini",
      previous_response_id=first.id,
      input="保持上一张图的主体和构图，把背景改成透明，并让云朵边缘更圆润。",
      tools=[{
          "type": "image_generation",
          "model": "gpt-image-1",
          "action": "edit",             # auto / generate / edit
      }],
  )

  save_image_from_response(second, "output/cloud-v2.png")
  ```

  ```python Gemini GenAI Chat theme={null}
  from google import genai
  from google.genai import types

  client = genai.Client(
      api_key="sk-your-api-key",
      http_options=types.HttpOptions(base_url="https://www.focusapi.cn"),
  )

  chat = client.chats.create(
      model="gemini-3.1-flash-image-preview",
      config=types.GenerateContentConfig(
          response_modalities=["TEXT", "IMAGE"],
          image_config=types.ImageConfig(
              aspect_ratio="1:1",
              image_size="1K",
          ),
      ),
  )

  first = chat.send_message(
      "生成一张极简蓝色云朵图标，白色背景，适合作为 App 图标。"
  )

  second = chat.send_message(
      "保持上一张图的主体和构图，把背景改成透明，并让云朵边缘更圆润。"
  )

  for part in second.parts:
      if image := part.as_image():
          image.save("cloud-icon.png")
          print("图片已保存到 cloud-icon.png")
      elif part.text and len(part.text) < 500:
          print(part.text)
  ```
</CodeGroup>

<Note>
  OpenAI 多轮改图需模型支持 **Responses API** 和 **`image_generation` 内置工具**（以模型广场为准）。`previous_response_id` 用于串联上下文；若只想强制改图，可在 tool 里加 `"action": "edit"`，强制新图用 `"action": "generate"`。Gemini 多轮示例使用 GenAI Chat 会话。普通 `/v1/images/generations` 不会自动记住上一轮图片。
</Note>

## Qwen / 豆包 / 其他热门图像模型

这类模型通常有两种接入方式：一种是平台适配后的 OpenAI 兼容 Images API，另一种是厂商原生 SDK 或原生参数。建议先用 curl 跑通，再根据模型广场说明选择 SDK。

<CodeGroup>
  ```bash cURL theme={null}
  curl https://www.focusapi.cn/v1/images/generations \
    -H "Authorization: Bearer sk-your-api-key" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "your-image-model-id",
      "prompt": "一张适合电商详情页的产品主图",
      "size": "1024x1024",
      "n": 1
    }'
  ```

  ```python OpenAI SDK theme={null}
  import base64
  from urllib.request import urlopen
  from openai import OpenAI

  client = OpenAI(
      base_url="https://www.focusapi.cn/v1",
      api_key="sk-your-api-key",
  )

  image = client.images.generate(
      model="your-image-model-id",
      prompt="一张适合电商详情页的产品主图",
      size="1024x1024",
      n=1,
      response_format="b64_json",
  )

  item = image.data[0]
  save_path = "focusapi-image.png"

  if item.b64_json:
      with open(save_path, "wb") as f:
          f.write(base64.b64decode(item.b64_json))
  elif item.url:
      with open(save_path, "wb") as f:
          f.write(urlopen(item.url).read())

  print(f"已保存: {save_path}")
  ```
</CodeGroup>

### 兼容图像模型参数

<AccordionGroup>
  <Accordion title="Qwen 图像模型">
    | 参数                | 说明            | 可选值                      |
    | ----------------- | ------------- | ------------------------ |
    | `model`           | 模型广场中的完整模型 ID | 以模型广场为准                  |
    | `prompt`          | 图片提示词         | 文本                       |
    | `size`            | 图片尺寸或比例       | 以模型广场为准                  |
    | `n`               | 生成张数          | 以模型广场为准                  |
    | `response_format` | 返回格式          | `url`、`b64_json`，以模型支持为准 |
  </Accordion>

  <Accordion title="豆包 / Seedream 图像模型">
    | 参数                | 说明              | 可选值                                                           |
    | ----------------- | --------------- | ------------------------------------------------------------- |
    | `model`           | 模型广场中的完整模型 ID   | 以模型广场为准                                                       |
    | `prompt`          | 图片提示词           | 文本                                                            |
    | `size`            | 图片尺寸或比例         | 常见如 `1024x1024`、`1024x1536`、`1536x1024`、`16:9`、`9:16`，以模型广场为准 |
    | `seed`            | 固定随机种子，便于复现相似结果 | 整数，范围以模型说明为准                                                  |
    | `negative_prompt` | 不希望出现在图片中的内容    | 文本                                                            |
    | `watermark`       | 是否带水印           | `true`、`false`，以模型支持为准                                        |
  </Accordion>

  <Accordion title="其他 OpenAI 兼容图像模型">
    | 参数                | 说明            | 可选值                      |
    | ----------------- | ------------- | ------------------------ |
    | `model`           | 模型广场中的完整模型 ID | 以模型广场为准                  |
    | `prompt`          | 图片提示词         | 文本                       |
    | `size`            | 图片尺寸或比例       | 以模型广场为准                  |
    | `n`               | 生成张数          | 以模型广场为准                  |
    | `response_format` | 返回格式          | `url`、`b64_json`，以模型支持为准 |
    | `extra_body`      | 传递厂商特殊参数      | 以模型广场和错误提示为准             |
  </Accordion>
</AccordionGroup>

### 常见特殊参数

| 模型版本               | 参数                | 说明              | 可选值                    |
| ------------------ | ----------------- | --------------- | ---------------------- |
| 扩散类 / Seedream 类模型 | `seed`            | 固定随机种子，便于复现相似结果 | 整数，范围以模型说明为准           |
| 扩散类 / Seedream 类模型 | `negative_prompt` | 不希望出现在图片中的内容    | 文本                     |
| 中文营销图模型            | `watermark`       | 是否带水印           | `true`、`false`，以模型支持为准 |
| 厂商原生模型             | `extra_body`      | 传递厂商特殊参数        | 以模型广场和错误提示为准           |

## 参数填写原则

* 生成任务先只传 `model`、`prompt`、`size`、`n` 跑通，再增加特殊参数。
* 同一厂商不同模型版本的可选值可能不同，尤其是 `size`、`quality`、`aspect_ratio`。
* 参数报错时，不要猜字段名；优先查看模型广场，或根据错误提示调整。
* 图片 URL 返回可能有有效期，生产环境建议及时转存。
* 需要基于已有图片修改时，不要用本文的文生图接口，改看 [图像编辑](/models/image-editing)。

## 异步图像任务

部分图像或高耗时模型可能返回 `task_id`，需要轮询任务状态，而不是等待同步响应。此类模型以模型广场说明为准，处理思路与 [视频生成](/models/video-generation) 类似。

## 常见问题

* Gemini 图片模型调用 `generate_images` 失败：`gemini-3.1-flash-image-preview` 等模型应使用 `generate_content` 或 Chat，并用 `part.as_image().save()` 保存；`generate_images` 仅适用于 `imagen-*` 模型。
* 只打印出一长串编码、没有保存图片：先调用 `part.as_image()` 保存，不要先 `print(part.text)`；若图片在 text 的 `data:image/...;base64,...` 里，需正则提取后解码保存。
* 保存的 PNG 为 0 KB 或报错 `'str' object has no attribute 'decode'`：`b64_json` 已是 base64 字符串，应使用 `base64.b64decode(item.b64_json)` 解码后再写入文件，不要对 `b64_json` 调用 `.decode()`，也不要把 base64 文本直接当二进制写入。
* 返回图片 URL 无法访问：检查 URL 有效期，或使用 `b64_json` 返回格式。
* 尺寸不支持：换成模型广场推荐尺寸。
* 请求很久后失败：看 [524 超时](/errors/524)，重任务优先使用异步任务。
* 生成被拦截：调整提示词，避免违反内容安全策略。
* 费用不确定：不同图片模型可能按次或按规格计费，见 [计费与用量](/billing/pricing)。
