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

# 图片生成与编辑

> 生成、编辑、解码与保存图片结果。

图片生成与[图片理解](/zh/guides/vision.md)是两种能力。先在部署中确认模型能调用 Images 接口；模型出现在列表里，不代表它支持生成、编辑或全部参数。

## 选择接口

| 操作 | 请求 | 返回 |
| - | - | - |
| [生成图片](/zh/api-reference/images-generations.md) | `POST /v1/images/generations`，JSON | `data[]` 图片结果 |
| [编辑图片](/zh/api-reference/images-edits.md) | `POST /v1/images/edits`，multipart 或模型支持的 JSON | `data[]` 图片结果 |

从 `model`、`prompt`、`n: 1` 开始；按模型文档选择 `size`、`quality`、`background` 和 `output_format`。不要把某个模型的尺寸、张数或格式限制套用于全部渠道。`response_format` 是结果包装方式（URL / Base64），`output_format` 是图片编码（PNG / JPEG / WebP），两者不同。

## Python：生成与编辑

按 [Python SDK](/zh/guides/python.md)准备环境，设置 `API_BASE_URL`（包含 `/v1`）、`API_KEY` 和图片模型的 `API_MODEL`。保存为 `images.py`。生成时运行 `python images.py generate`；编辑前再设置 `API_IMAGE_PATH` 为本地图片路径，运行 `python images.py edit`。编辑会将文件发送到所配置的网关及其上游。

示例不强制指定返回格式，以兼容模型默认值：优先解码 `b64_json`，否则输出 `url`。PNG/JPEG/WebP 根据文件头选择扩展名；这不是完整的图片有效性检测。输出到当前目录，不覆盖已有文件。

```python theme={null}
import base64
import binascii
import os
import sys
from pathlib import Path
from openai import OpenAI, APIConnectionError, APIStatusError

mode = sys.argv[1] if len(sys.argv) == 2 else ""
if mode not in ("generate", "edit"):
    raise SystemExit("Usage: python images.py generate|edit")

with OpenAI(base_url=os.environ["API_BASE_URL"].rstrip("/"),
            api_key=os.environ["API_KEY"], timeout=180.0, max_retries=0) as client:
    try:
        if mode == "generate":
            result = client.images.generate(
                model=os.environ["API_MODEL"], n=1,
                prompt="A small blue ceramic cup on a plain white background.",
            )
        else:
            with Path(os.environ["API_IMAGE_PATH"]).open("rb") as source:
                result = client.images.edit(
                    model=os.environ["API_MODEL"], image=source, n=1,
                    prompt="Change the cup to green, preserving the composition.",
                )
        if not result.data:
            raise ValueError("No image payload.")
        for index, item in enumerate(result.data, start=1):
            if item.b64_json:
                data = base64.b64decode(item.b64_json, validate=True)
                if data.startswith(b"\x89PNG\r\n\x1a\n"):
                    extension = "png"
                elif data.startswith(b"\xff\xd8\xff"):
                    extension = "jpg"
                elif data.startswith(b"RIFF") and data[8:12] == b"WEBP":
                    extension = "webp"
                else:
                    raise ValueError("Unsupported image bytes.")
                output = Path(f"image-{index}.{extension}")
                with output.open("xb") as target:
                    target.write(data)
                print(f"Saved {output}")
            elif item.url:
                # Do not send the gateway API key to this URL.
                print(item.url)
            else:
                raise ValueError("Image entry has no payload.")
    except APIStatusError as error:
        raise SystemExit(f"Request failed (HTTP {error.status_code}). Check the request logs.")
    except APIConnectionError:
        raise SystemExit("Connection failed; do not automatically resubmit generation.")
    except (ValueError, binascii.Error, OSError):
        raise SystemExit("Cannot save image. Check the response format and output files.")
```

## 编辑输入与结果保存

multipart 的文件字段用 `image`；支持多图的渠道可能要求重复 `image[]`。SDK 会生成 boundary，不要手动把上传请求设成 `application/json`。蒙版通常用 `mask` 文件，但透明区域、尺寸和格式规则需核对具体模型。

JSON 编辑形式并不统一。本参考记录 `images: [{"image_url": "https://..."}]` 的常用形式，需先确认渠道支持；部分插件使用其他字段。远程地址必须能被处理该请求的服务访问，本地路径不能作为远程 URL。项目的通用 Files API 未实现，不要把上游文档中的“先上传 Files 再传 file\_id”直接照搬。

URL 可能过期，需及时保存；下载时不要把网关 Bearer 密钥附到第三方图片 URL。Base64 应解码后写入二进制文件。先检查 HTTP 错误，再检查图片字段；只有 `revised_prompt` 不代表生成成功。若一次返回多张，保存失败时之前的文件可能已经写入。

## 等待、流式与重试

本例使用同步结果。任务插件的 Images 协议也会在当前请求内等待结果，超时可能返回 `504 task_timeout`，断开连接后任务仍可能继续。超时不等于没有提交，不要立即重复生成；先查请求/任务日志。

直连转发渠道可能支持图片 SSE，但插件 Images 协议没有通用流式模式。不要把 `stream: true` 当作所有图片模型可用的参数，也不要用 Chat 文本流的解析器读取图片事件。

参考：[OpenAI 图片生成说明](https://developers.openai.com/api/docs/guides/image-generation)。该链接说明上游协议，实际可用能力以当前网关为准。

[Read in English](/en/guides/image-generation.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.