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

# 创建图像

> 使用 CometAPI POST /v1/images/generations，通过兼容 OpenAI 的图像模型和模型专属控制项来创建图像。

使用此路由可在 CometAPI 上通过兼容 OpenAI 的请求格式，根据文本创建图像。

## 官方参考

* 在使用 `background`、`output_compression`、streaming 或未来的 GPT 图像选项等模型专属控制项之前，请先阅读 [OpenAI 图像生成指南](https://developers.openai.com/api/docs/guides/image-generation)。
* 当前参数列表请参考 [OpenAI 创建图像参考](https://developers.openai.com/api/reference/resources/images/methods/generate)。

## 先选择模型

* 对于带有 `output_format`、`quality` 或 `background` 等控制项的文生图请求，请使用 `gpt-image-2` 这类 GPT 图像模型
* 当你明确需要该提供商时，使用 `qwen-image`，但请将 `n` 保持为 1
* 从[模型页面](/zh-Hans/overview/models)选择当前可用的图像 model ID

## 安全的首次请求

* 从 `gpt-image-2` 开始
* 将 `size` 保持为 `1024x1024`
* GPT 图像模型会在 `b64_json` 中返回 base64 编码的图像数据；请将其解码后保存为图像文件
* 仅当你需要特定编码图像类型（如 `jpeg`）时再添加 `output_format`
* 在添加 `background`、`output_compression` 或流式输出（Streaming）之前，请先查看 OpenAI 图像生成指南
* 在添加批量生成或风格调优之前，先使用一个 Prompt 和一张输出图像

## 运行异步图像任务

当图像任务运行时间较长，且你的客户端更适合“提交并轮询”流程而不是保持一个 HTTP 连接持续打开时，请使用 `async: true`。创建请求会返回 `data.task_id`。

轮询[获取图像生成任务](/api/image/openai/image-generation-task)，直到 `data.status` 为 `success` 或 `failure`。

`async` 字段是此路由上的 CometAPI 扩展，并不是 OpenAI 参数。OpenAI 为 GPT 图像模型提供了 `stream` 和 `partial_images` 的文档说明。CometAPI 的异步任务模式会返回 JSON 任务元数据，并通过轮询来获取结果。

请对以下已文档化的 model ID 使用异步任务模式：`gpt-image-2` 和 `doubao-seedream-4-0-250828`。对于其他图像模型，请使用同步生成或流式输出，除非该模型的文档明确说明支持异步任务。

当请求同时包含 `async: true` 和 `stream: true` 时，异步任务模式优先。创建请求将返回 JSON 任务元数据，而不是 SSE 流。

## 模型专属请求行为

* `response_format` 仅适用于 DALL·E 模型；GPT 图像模型会返回 base64 数据并忽略它
* GPT 图像模型使用 GPT 专属控制项，例如 `output_format`、`quality`、`background` 和 `output_compression`
* 请遵循 OpenAI 图像生成指南以了解最新的模型专属选项
* `qwen-image` 不支持 `n > 1`

<Warning>
  生成的图像必须符合提供商使用政策。请勿发送违法、暴力、色情或侵犯版权的 Prompt。
</Warning>


## OpenAPI

````yaml api/openapi/image/openai/post-images.openapi.json POST /v1/images/generations
openapi: 3.1.0
info:
  title: Images API
  version: 1.0.0
  description: >-
    Create images through the OpenAI-compatible CometAPI image generation route.
    Request parameters vary by model. For the latest model-specific controls,
    refer to the OpenAI image generation guide:
    https://developers.openai.com/api/docs/guides/image-generation
servers:
  - url: https://api.cometapi.com
security:
  - bearerAuth: []
paths:
  /v1/images/generations:
    post:
      summary: Create images
      description: >-
        Generate images from a text prompt using OpenAI-compatible request
        shapes on CometAPI. For the latest model-specific output controls and
        parameter support, refer to the OpenAI image generation guide:
        https://developers.openai.com/api/docs/guides/image-generation
      operationId: images
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - model
                - prompt
              properties:
                model:
                  type: string
                  description: >-
                    The image generation model to use. Choose a current model
                    from the [Models page](/overview/models).
                  default: gpt-image-2
                prompt:
                  type: string
                  description: Text description of the image you want to generate.
                  example: A paper boat floating on calm water at sunrise.
                'n':
                  type: integer
                  description: >-
                    Number of images to generate. Keep this at 1 for the
                    broadest compatibility.
                  default: 1
                quality:
                  type: string
                  description: >-
                    Quality setting for models that support it. See the OpenAI
                    image generation guide for the latest model-specific values.
                size:
                  type: string
                  description: >-
                    Requested output size. Supported values depend on the
                    selected model. See the OpenAI image generation guide for
                    the latest model-specific ranges.
                  example: 1024x1024
                response_format:
                  type: string
                  description: >-
                    The response container for `dall-e-2` and `dall-e-3`. This
                    parameter is not supported for GPT image models, which
                    return base64-encoded image data.
                  enum:
                    - url
                    - b64_json
                output_format:
                  type: string
                  description: >-
                    The encoded image type for GPT image model results, such as
                    `png`, `jpeg`, or `webp`. See the OpenAI image generation
                    guide for current GPT image output controls.
                  example: jpeg
                stream:
                  type: boolean
                  description: >-
                    Set this to `true` to receive server-sent image generation
                    events instead of waiting for the completed JSON response.
                    Streaming responses use `text/event-stream` and can include
                    final events such as `image_generation.completed`. When
                    `stream` and `async` are both `true`, async task mode takes
                    precedence and the create request returns JSON instead of a
                    streaming image response.
                  default: false
                async:
                  type: boolean
                  description: >-
                    CometAPI asynchronous task mode. Set this to `true` to
                    return immediately with `data.task_id`, then poll `GET
                    /v1/images/generations/{task_id}` for the final image data.
                    Documented model IDs for this mode: `gpt-image-2` and
                    `doubao-seedream-4-0-250828`. This is a CometAPI extension,
                    not an OpenAI parameter. When `async` and `stream` are both
                    `true`, async takes precedence and returns JSON task
                    metadata instead of an SSE stream.
                  default: false
              default:
                model: gpt-image-2
                prompt: A paper boat floating on calm water at sunrise.
                'n': 1
                size: 1024x1024
                output_format: jpeg
            examples:
              gpt_image:
                summary: GPT image generation (gpt-image-2)
                value:
                  model: gpt-image-2
                  prompt: A paper boat floating on calm water at sunrise.
                  quality: low
                  size: 1024x1024
                  output_format: jpeg
              streaming_image:
                summary: Streaming image generation
                value:
                  model: gpt-image-2
                  prompt: A paper boat floating on calm water at sunrise.
                  quality: low
                  size: 1024x1024
                  output_format: jpeg
                  stream: true
              async_image:
                summary: Async image generation
                value:
                  model: gpt-image-2
                  prompt: A paper boat floating on calm water at sunrise.
                  quality: low
                  size: 1024x1024
                  output_format: jpeg
                  async: true
              gpt_image_1:
                summary: GPT image generation (gpt-image-1)
                value:
                  model: gpt-image-1
                  prompt: A paper boat floating on calm water at sunrise.
                  quality: low
                  size: 1024x1024
      responses:
        '200':
          description: >-
            Image generation result. Synchronous requests return completed image
            data. Async requests return a task response with `data.task_id`.
          content:
            application/json:
              schema:
                oneOf:
                  - type: object
                    title: Completed image response
                    required:
                      - created
                      - data
                    properties:
                      created:
                        type: integer
                        description: Unix timestamp for the completed generation.
                      background:
                        type: string
                        description: Background mode returned by models that expose it.
                      output_format:
                        type: string
                        description: Encoded image type returned by GPT image models.
                      quality:
                        type: string
                        description: Quality level returned by models that expose it.
                      size:
                        type: string
                        description: Output size returned by models that expose it.
                      usage:
                        type: object
                        description: >-
                          Token usage details when returned by the selected
                          model.
                        properties:
                          input_tokens:
                            type: integer
                          output_tokens:
                            type: integer
                          total_tokens:
                            type: integer
                          input_tokens_details:
                            type: object
                            properties:
                              image_tokens:
                                type: integer
                              text_tokens:
                                type: integer
                          output_tokens_details:
                            type: object
                            properties:
                              image_tokens:
                                type: integer
                              text_tokens:
                                type: integer
                      data:
                        type: array
                        items:
                          type: object
                          properties:
                            url:
                              type: string
                              description: >-
                                Temporary image URL when the selected model
                                supports URL output.
                            b64_json:
                              type: string
                              description: >-
                                Base64-encoded image payload for models that
                                return inline content.
                            revised_prompt:
                              type: string
                              description: Provider-rewritten prompt, when available.
                  - type: object
                    title: Async task response
                    required:
                      - code
                      - data
                    properties:
                      code:
                        type: string
                        description: >-
                          Request status code. A successful async submit returns
                          `success`.
                        example: success
                      message:
                        type: string
                        description: Optional status message.
                      data:
                        type: object
                        required:
                          - task_id
                          - status
                          - data
                        properties:
                          task_id:
                            type: string
                            description: >-
                              Task ID to pass to `GET
                              /v1/images/generations/{task_id}`.
                          status:
                            type: string
                            description: Task state for the submitted image generation job.
                            enum:
                              - pending
                              - success
                              - failure
                          data:
                            type: array
                            description: >-
                              Empty at submit time. Poll the task endpoint to
                              receive final image data.
                            items:
                              type: object
                    example:
                      code: success
                      message: ''
                      data:
                        task_id: <task_id>
                        status: pending
                        data: []
              example:
                created: 1781075000
                background: opaque
                output_format: jpeg
                quality: low
                size: 1024x1024
                usage:
                  input_tokens: 13
                  input_tokens_details:
                    image_tokens: 0
                    text_tokens: 13
                  output_tokens: 196
                  output_tokens_details:
                    image_tokens: 196
                    text_tokens: 0
                  total_tokens: 209
                data:
                  - b64_json: /9j/4AAQSkZJRgABAQAAAQABAAD...
            text/event-stream:
              schema:
                type: string
                description: >-
                  Server-sent events returned when `stream` is `true`. Events
                  can include image generation progress and final image data.
              example: >+
                event: image_generation.completed

                data:
                {"created_at":1783305600,"type":"image_generation.completed","b64_json":"<base64-image-data>"}

      x-codeSamples:
        - lang: Shell
          label: Default
          source: |
            curl https://api.cometapi.com/v1/images/generations \
              -H "Authorization: Bearer $COMETAPI_KEY" \
              -H "Content-Type: application/json" \
              -d '{
                "model": "gpt-image-2",
                "prompt": "A paper boat floating on calm water at sunrise.",
                "quality": "low",
                "size": "1024x1024",
                "output_format": "jpeg"
              }'
        - lang: Python
          label: Default
          source: |
            import base64
            import os
            from openai import OpenAI

            client = OpenAI(
                base_url="https://api.cometapi.com/v1",
                api_key=os.environ["COMETAPI_KEY"],
            )

            result = client.images.generate(
                model="gpt-image-2",
                prompt="A paper boat floating on calm water at sunrise.",
                quality="low",
                size="1024x1024",
                output_format="jpeg",
            )

            image_bytes = base64.b64decode(result.data[0].b64_json)
            with open("boat.jpg", "wb") as f:
                f.write(image_bytes)
        - lang: JavaScript
          label: Default
          source: >
            import fs from "node:fs";

            import OpenAI from "openai";


            const client = new OpenAI({
                baseURL: "https://api.cometapi.com/v1",
                apiKey: process.env.COMETAPI_KEY,
            });


            const result = await client.images.generate({
                model: "gpt-image-2",
                prompt: "A paper boat floating on calm water at sunrise.",
                quality: "low",
                size: "1024x1024",
                output_format: "jpeg",
            });


            fs.writeFileSync("boat.jpg", Buffer.from(result.data[0].b64_json,
            "base64"));
        - lang: Shell
          label: Streaming request
          source: |
            curl -N https://api.cometapi.com/v1/images/generations \
              -H "Authorization: Bearer $COMETAPI_KEY" \
              -H "Content-Type: application/json" \
              -d '{
                "model": "gpt-image-2",
                "prompt": "A paper boat floating on calm water at sunrise.",
                "quality": "low",
                "size": "1024x1024",
                "output_format": "jpeg",
                "stream": true
              }'
        - lang: Python
          label: Streaming request
          source: |
            import json
            import os
            import urllib.request

            payload = {
                "model": "gpt-image-2",
                "prompt": "A paper boat floating on calm water at sunrise.",
                "quality": "low",
                "size": "1024x1024",
                "output_format": "jpeg",
                "stream": True,
            }

            request = urllib.request.Request(
                "https://api.cometapi.com/v1/images/generations",
                data=json.dumps(payload).encode("utf-8"),
                headers={
                    "Authorization": "Bearer " + os.environ["COMETAPI_KEY"],
                    "Content-Type": "application/json",
                },
                method="POST",
            )

            with urllib.request.urlopen(request) as response:
                for raw_line in response:
                    line = raw_line.decode("utf-8").strip()
                    if line:
                        print(line)
        - lang: JavaScript
          label: Streaming request
          source: >
            const response = await
            fetch("https://api.cometapi.com/v1/images/generations", {
              method: "POST",
              headers: {
                Authorization: `Bearer ${process.env.COMETAPI_KEY}`,
                "Content-Type": "application/json",
              },
              body: JSON.stringify({
                model: "gpt-image-2",
                prompt: "A paper boat floating on calm water at sunrise.",
                quality: "low",
                size: "1024x1024",
                output_format: "jpeg",
                stream: true,
              }),
            });


            const decoder = new TextDecoder();

            for await (const chunk of response.body) {
              process.stdout.write(decoder.decode(chunk));
            }
        - lang: Shell
          label: Async request
          source: |
            curl https://api.cometapi.com/v1/images/generations \
              -H "Authorization: Bearer $COMETAPI_KEY" \
              -H "Content-Type: application/json" \
              -d '{
                "model": "gpt-image-2",
                "prompt": "A paper boat floating on calm water at sunrise.",
                "quality": "low",
                "size": "1024x1024",
                "output_format": "jpeg",
                "async": true
              }'
        - lang: Python
          label: Async request
          source: |
            import os
            import requests

            response = requests.post(
                "https://api.cometapi.com/v1/images/generations",
                headers={
                    "Authorization": "Bearer " + os.environ["COMETAPI_KEY"],
                    "Content-Type": "application/json",
                },
                json={
                    "model": "gpt-image-2",
                    "prompt": "A paper boat floating on calm water at sunrise.",
                    "quality": "low",
                    "size": "1024x1024",
                    "output_format": "jpeg",
                    "async": True,
                },
            )

            result = response.json()
            print(result["data"]["task_id"])
        - lang: JavaScript
          label: Async request
          source: >
            const response = await
            fetch("https://api.cometapi.com/v1/images/generations", {
              method: "POST",
              headers: {
                Authorization: `Bearer ${process.env.COMETAPI_KEY}`,
                "Content-Type": "application/json",
              },
              body: JSON.stringify({
                model: "gpt-image-2",
                prompt: "A paper boat floating on calm water at sunrise.",
                quality: "low",
                size: "1024x1024",
                output_format: "jpeg",
                async: true,
              }),
            });


            const result = await response.json();

            console.log(result.data.task_id);
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: Bearer token authentication. Use your CometAPI key.

````