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

# Gemini 图片编辑 API

> 通过 BetterToken 的 Gemini 原生 API 调用 Nano Banana 编辑图片。提供参考图和编辑指令，在线调试请求，并了解内嵌图片与返回结果的处理方式。

export const GeminiImageInput = ({labels}) => {
  const [images, setImages] = useState([]);
  const [busy, setBusy] = useState(false);
  const [feedback, setFeedback] = useState("");
  const selection = useRef(0);
  const inputId = useId();
  const readImages = async event => {
    const version = ++selection.current;
    const files = Array.from(event.target.files || []);
    setImages([]);
    setFeedback("");
    if (files.some(file => !["image/png", "image/jpeg"].includes(file.type))) {
      setFeedback(labels[4]);
      setBusy(false);
      return;
    }
    setBusy(true);
    try {
      const next = await Promise.all(files.map(file => new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => resolve({
          name: file.name,
          type: file.type,
          data: String(reader.result).split(",")[1]
        });
        reader.onerror = reject;
        reader.onabort = reject;
        reader.readAsDataURL(file);
      })));
      if (version === selection.current) setImages(next);
    } catch {
      if (version === selection.current) setFeedback(labels[5]);
    } finally {
      if (version === selection.current) setBusy(false);
    }
  };
  const copy = async value => {
    try {
      await navigator.clipboard.writeText(value);
      setFeedback(labels[2]);
    } catch {
      setFeedback(labels[3]);
    }
  };
  return <section className="bt-gemini-input not-prose" aria-label={labels[0]}>
      <label htmlFor={inputId}>{labels[0]}</label>
      <input id={inputId} type="file" accept="image/png,image/jpeg" multiple onChange={readImages} />
      <p>{labels[7]}</p>
      <p role="status" aria-live="polite">{busy ? labels[6] : feedback}</p>
      {images.map((image, index) => <div key={index} className="bt-gemini-input-image">
          <div className="bt-gemini-input-header">
            <img src={"data:" + image.type + ";base64," + image.data} alt={image.name} />
            <span>{image.name}</span>
            <code>{image.type}</code>
            <button type="button" title={labels[1]} aria-label={labels[1] + " " + image.name} onClick={() => copy(image.data)}><Icon icon="copy" size={16} /></button>
          </div>
          <textarea aria-label={labels[1] + " " + image.name} rows={3} readOnly value={image.data} spellCheck={false} />
        </div>)}
    </section>;
};

向 Nano Banana Pro、2 或 2.1 提交参考图和编辑指令，生成修改后的图片。

`POST /v1beta/models/{model}:generateContent`

文生图和图片编辑使用同一个接口；图片编辑的请求中需要增加参考图。

## 准备参考图

文字指令和每张图片分别放在独立 part 中。`inlineData.data` 填写原始 base64，不包含 Data URL 前缀。参考图使用 PNG 或 JPEG；接口接收 JSON，不使用 multipart 上传或图片 URL。

发送前必须将示例中的 `REPLACE_WITH_IMAGE_BASE64` 替换成你的图片 base64，并根据图片填写 `inlineData.mimeType`。示例编辑指令针对杯子；使用其他图片时请同时修改指令。

<GeminiImageInput labels={["参考图片","复制 base64","已复制","请选中下方 base64 复制。","请选择 PNG 或 JPEG 图片。","图片读取失败，请重新选择。","正在准备图片...","图片仅在本地转换。在 Playground 中，将复制的 base64 填入 inlineData.data，并将 inlineData.mimeType 设为显示的 MIME 类型。增加参考图时，每张图片使用独立 part。"]} />

## 在线调试

准备好参考图后，在 **x-goog-api-key** 中填写 BetterToken API Key，并选择 **model**。在 **contents** 中填写编辑指令和图片数据，检查 `inlineData.data` 已替换、`inlineData.mimeType` 与文件一致，再点击 **Send**。

<Note>
  点击 **Send** 会发起真实生成请求，可能产生费用。接口同步等待生成完成；超时或断连后，请先核对消费记录和请求结果，再决定是否重新发送。
</Note>

三款均提供 `1K`、`2K`、`4K`。Nano Banana 2 和 2.1 支持 14 种比例，Pro 支持 10 种。 `X-BetterToken-Max-Images` 是允许返回并计费的图片数量上限，不保证生成对应张数。 [比例列表](/zh/api-reference/nano-banana#aspect-ratios)

<Warning>
  BetterToken API 不支持搜索生图，包括 Google 网页搜索和图片搜索增强。不要添加搜索工具。
</Warning>

本接入方式使用非流式 `generateContent`。不支持 Files / `fileData`、Batch、Interactions 或流式调用。

## 读取响应

图片位于 `candidates[].content.parts[].inlineData`。遍历所有 part，跳过 `thought: true`，解码 `data`，并根据 `mimeType` 选择文件后缀。不要假定图片总在第一个 part，也不要一律保存成 PNG。

## 相关文档

* [文生图](/zh/api-reference/gemini-images-generations)
* [SDK、图片保存与连续编辑](/zh/api-reference/nano-banana)
* [模型介绍](/zh/model-updates/nano-banana)
* <a href={"https://bettertoken.ai/pricing"}>模型广场</a>


## OpenAPI

````yaml api-reference/gemini-images-edits.zh.json POST /v1beta/models/{model}:generateContent
openapi: 3.1.0
info:
  title: Gemini 图片编辑 API
  description: >-
    通过 BetterToken 的 Gemini 原生 API 调用 Nano Banana
    编辑图片。提供参考图和编辑指令，在线调试请求，并了解内嵌图片与返回结果的处理方式。
  version: 1.0.0
servers:
  - url: https://bettertoken.ai
security:
  - geminiApiKey: []
paths:
  /v1beta/models/{model}:generateContent:
    post:
      summary: Gemini 图片编辑 API
      description: >-
        向 Nano Banana Pro、2 或 2.1 提交参考图和编辑指令，生成修改后的图片。 BetterToken API
        不支持搜索生图，包括 Google 网页搜索和图片搜索增强。不要添加搜索工具。
      operationId: editGeminiImage_zh
      parameters:
        - name: model
          in: path
          required: true
          description: BetterToken 模型 ID，选择三款 Nano Banana 模型之一。
          schema:
            type: string
            enum:
              - nano-banana-pro
              - nano-banana-2
              - nano-banana-2.1
            default: nano-banana-2.1
        - name: X-BetterToken-Max-Images
          in: header
          description: 允许返回并计费的图片数量上限，不保证生成对应张数。默认值为 1。
          schema:
            type: integer
            minimum: 1
            maximum: 4
            default: 1
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - contents
              properties:
                contents:
                  type: array
                  description: 对话内容。连续编辑时保留完整模型 content 和 thoughtSignature。
                  minItems: 1
                  items:
                    type: object
                    required:
                      - parts
                    properties:
                      role:
                        type: string
                        description: 新请求使用 user；编辑历史中的模型响应使用 model。
                        enum:
                          - user
                          - model
                        default: user
                      parts:
                        type: array
                        description: 文字和图片内容。text 和 inlineData 分别放在独立 part 中。
                        minItems: 1
                        items:
                          anyOf:
                            - type: object
                              required:
                                - text
                              properties:
                                text:
                                  type: string
                                  description: 图片描述或编辑指令。
                                  example: 将杯子改为红色，保持杯子形状、背景和光线不变。
                              additionalProperties: true
                            - type: object
                              required:
                                - inlineData
                              properties:
                                inlineData:
                                  type: object
                                  description: 以 base64 内嵌的参考图。
                                  required:
                                    - mimeType
                                    - data
                                  properties:
                                    mimeType:
                                      type: string
                                      description: 参考图片的 MIME 类型。
                                      enum:
                                        - image/png
                                        - image/jpeg
                                      example: image/png
                                    data:
                                      type: string
                                      description: >-
                                        原始图片字节的 base64，不包含 Data URL
                                        前缀。发送前必须用你自己的 PNG 或 JPEG 图片数据替换
                                        REPLACE_WITH_IMAGE_BASE64。
                                      contentEncoding: base64
                                      example: REPLACE_WITH_IMAGE_BASE64
                                  additionalProperties: false
                              additionalProperties: true
                    additionalProperties: false
                generationConfig:
                  type: object
                  description: 图片生成配置。
                  properties:
                    responseModalities:
                      type: array
                      description: 显式请求图片输出。
                      items:
                        type: string
                        enum:
                          - IMAGE
                      default:
                        - IMAGE
                    candidateCount:
                      type: integer
                      enum:
                        - 1
                      default: 1
                      description: 省略或设为整数 1，不要在根级传 n。
                    imageConfig:
                      type: object
                      description: 输出图片配置。
                      properties:
                        imageSize:
                          type: string
                          description: 输出分辨率，K 必须大写。
                          enum:
                            - 1K
                            - 2K
                            - 4K
                          default: 1K
                        aspectRatio:
                          type: string
                          description: 输出比例。Pro 支持 10 种，2 和 2.1 还支持 1:4、4:1、1:8、8:1。
                          enum:
                            - '1:1'
                            - '1:4'
                            - '1:8'
                            - '2:3'
                            - '3:2'
                            - '3:4'
                            - '4:1'
                            - '4:3'
                            - '4:5'
                            - '5:4'
                            - '8:1'
                            - '9:16'
                            - '16:9'
                            - '21:9'
                          default: '1:1'
                      additionalProperties: false
                  additionalProperties: false
              additionalProperties: false
            example:
              contents:
                - role: user
                  parts:
                    - text: 将杯子改为红色，保持杯子形状、背景和光线不变。
                    - inlineData:
                        mimeType: image/png
                        data: REPLACE_WITH_IMAGE_BASE64
              generationConfig:
                responseModalities:
                  - IMAGE
                candidateCount: 1
                imageConfig:
                  imageSize: 1K
                  aspectRatio: '1:1'
      responses:
        '200':
          description: 生成结果。检查最终图片 part 和 finishReason。
          content:
            application/json:
              schema:
                type: object
                properties:
                  candidates:
                    type: array
                    items:
                      type: object
                      properties:
                        content:
                          type: object
                          properties:
                            role:
                              type: string
                            parts:
                              type: array
                              items:
                                type: object
                                properties:
                                  text:
                                    type: string
                                  thought:
                                    type: boolean
                                  thoughtSignature:
                                    type: string
                                  inlineData:
                                    type: object
                                    properties:
                                      mimeType:
                                        type: string
                                      data:
                                        type: string
                                        contentEncoding: base64
                        finishReason:
                          type: string
                  promptFeedback:
                    type: object
                    additionalProperties: true
                  usageMetadata:
                    type: object
                    additionalProperties: true
              example:
                candidates:
                  - content:
                      role: model
                      parts:
                        - inlineData:
                            mimeType: image/png
                            data: BASE64_IMAGE_DATA
                    finishReason: STOP
        '400':
          description: 参数无效或功能不受支持。
        '401':
          description: API Key 缺失或无效。
        '402':
          description: 余额不足。
        '429':
          description: 触发限流或上游繁忙。
        '500':
          description: 生成服务异常，请先核对请求结果再重试。
components:
  securitySchemes:
    geminiApiKey:
      type: apiKey
      in: header
      name: x-goog-api-key
      description: BetterToken API Key。

````

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