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

# Gemini 3.1 Flash Image

> 通过 Gemini API 调用 Google Gemini 3.1 Flash Image 进行 AI 图片生成与编辑。

Gemini 3.1 Flash Image 是 Google 的图片生成模型，通过 Anyfast 以原生 Gemini API 提供服务。支持文字生成图片，也可传入参考图片进行图片编辑。

<Info>
  Google 已于 2026 年 5 月 28 日将 `gemini-3.1-flash-image` 发布为 Nano Banana 2 的正式版（GA）。请使用这个稳定模型 ID 替代 `gemini-3.1-flash-image-preview`，后者已弃用并计划于 2026 年 6 月 25 日关停。
</Info>

## 核心能力

* **文生图** — 根据文本描述生成图片
* **图片编辑** — 在 `inline_data` 中传入参考图，配合文字指令进行编辑
* **宽高比控制** — `1:1`、`4:3`、`3:4`、`16:9`、`9:16`
* **分辨率控制** — `512`（512px）、`1K`（\~1024px）、`2K`（\~2048px）、`4K`（\~4096px，按长边）
* **多模态输出** — 通过 `responseModalities: ["TEXT", "IMAGE"]` 同时返回图片和文字说明

> **注意：** 如果需要生成的图片返回 URL，请在创建 API 令牌时选择 **Aggregate-NanoUrl** 分组。

## 文生图示例

<CodeGroup>
  ```bash cURL theme={null}
  curl "https://www.anyfast.ai/v1beta/models/gemini-3.1-flash-image:generateContent?key=YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "contents": [
        {
          "role": "user",
          "parts": [
            { "text": "生成一张山间日落的图片" }
          ]
        }
      ],
      "generationConfig": {
        "responseModalities": ["TEXT", "IMAGE"],
        "imageConfig": {
          "aspectRatio": "16:9",
          "imageSize": "1K"
        }
      }
    }'
  ```

  ```python Python theme={null}
  import requests, base64

  url = "https://www.anyfast.ai/v1beta/models/gemini-3.1-flash-image:generateContent"
  response = requests.post(url, params={"key": "YOUR_API_KEY"}, json={
      "contents": [
          {
              "role": "user",
              "parts": [{"text": "生成一张山间日落的图片"}]
          }
      ],
      "generationConfig": {
          "responseModalities": ["TEXT", "IMAGE"],
          "imageConfig": {"aspectRatio": "16:9", "imageSize": "1K"}
      }
  })

  for part in response.json()["candidates"][0]["content"]["parts"]:
      if "inline_data" in part:
          with open("output.jpg", "wb") as f:
              f.write(base64.b64decode(part["inline_data"]["data"]))
          print("图片已保存至 output.jpg")
      elif "text" in part:
          print("说明文字：", part["text"])
  ```

  ```python GenAI SDK theme={null}
  import google.genai as genai

  client = genai.Client(api_key="YOUR_API_KEY")

  response = client.models.generate_content(
      model="gemini-3.1-flash-image",
      contents="生成一张山间日落的图片",
      config={
          "responseModalities": ["TEXT", "IMAGE"],
          "imageConfig": {
              "aspectRatio": "16:9",
              "imageSize": "1K"
          }
      }
  )

  for candidate in response.candidates:
      for part in candidate.content.parts:
          if part.inline_data:
              with open("output.jpg", "wb") as f:
                  f.write(part.inline_data.data)
              print("图片已保存至 output.jpg")
          elif part.text:
              print("说明文字：", part.text)
  ```
</CodeGroup>

## 图片编辑示例（传入参考图）

在同一个 `parts` 数组中同时传入 `text` 指令和 `inline_data` 参考图。

<CodeGroup>
  ```bash cURL theme={null}
  # 先将图片转为 base64：
  # BASE64=$(base64 -i your_photo.jpg)
  #
  # 然后发送请求：
  curl "https://www.anyfast.ai/v1beta/models/gemini-3.1-flash-image:generateContent?key=YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "contents": [
        {
          "role": "user",
          "parts": [
            {
              "text": "这是我的一张照片，请在我旁边加一只羊驼"
            },
            {
              "inline_data": {
                "mime_type": "image/jpeg",
                "data": "<YOUR_BASE64_ENCODED_IMAGE>"
              }
            }
          ]
        }
      ],
      "generationConfig": {
        "responseModalities": ["TEXT", "IMAGE"],
        "imageConfig": {
          "aspectRatio": "1:1",
          "imageSize": "1K"
        }
      }
    }'
  ```

  ```python Python theme={null}
  import requests, base64

  # 读取并编码参考图片
  with open("your_photo.jpg", "rb") as f:
      image_b64 = base64.b64encode(f.read()).decode("utf-8")

  url = "https://www.anyfast.ai/v1beta/models/gemini-3.1-flash-image:generateContent"
  response = requests.post(url, params={"key": "YOUR_API_KEY"}, json={
      "contents": [
          {
              "role": "user",
              "parts": [
                  {
                      "text": "这是我的一张照片，请在我旁边加一只羊驼"
                  },
                  {
                      "inline_data": {
                          "mime_type": "image/jpeg",
                          "data": image_b64          # ← 将 base64 字符串粘贴至此
                      }
                  }
              ]
          }
      ],
      "generationConfig": {
          "responseModalities": ["TEXT", "IMAGE"],
          "imageConfig": {"aspectRatio": "1:1", "imageSize": "1K"}
      }
  })

  for part in response.json()["candidates"][0]["content"]["parts"]:
      if "inline_data" in part:
          with open("output.jpg", "wb") as f:
              f.write(base64.b64decode(part["inline_data"]["data"]))
          print("图片已保存至 output.jpg")
      elif "text" in part:
          print("说明文字：", part["text"])
  ```

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

  client = genai.Client(api_key="YOUR_API_KEY")

  # 读取图片
  with open("your_photo.jpg", "rb") as f:
      image_bytes = f.read()

  response = client.models.generate_content(
      model="gemini-3.1-flash-image",
      contents=[
          "这是我的一张照片，请在我旁边加一只羊驼",
          types.Part.from_bytes(data=image_bytes, mime_type="image/jpeg")
      ],
      config={
          "responseModalities": ["TEXT", "IMAGE"],
          "imageConfig": {
              "aspectRatio": "1:1",
              "imageSize": "1K"
          }
      }
  )

  for candidate in response.candidates:
      for part in candidate.content.parts:
          if part.inline_data:
              with open("output.jpg", "wb") as f:
                  f.write(part.inline_data.data)
              print("图片已保存至 output.jpg")
          elif part.text:
              print("说明文字：", part.text)
  ```
</CodeGroup>

## 参数说明

| 参数                                         | 类型     | 必填 | 说明                                          |
| ------------------------------------------ | ------ | -- | ------------------------------------------- |
| `key`                                      | string | 是  | API 密钥（查询参数）                                |
| `contents[].parts[].text`                  | string | 是  | 文字提示或指令                                     |
| `contents[].parts[].inline_data.mime_type` | string | 否  | 参考图类型：`image/jpeg`、`image/png`、`image/webp` |
| `contents[].parts[].inline_data.data`      | string | 否  | Base64 编码的参考图数据                             |
| `generationConfig.responseModalities`      | array  | 是  | `["IMAGE"]` 或 `["TEXT", "IMAGE"]`           |
| `generationConfig.imageConfig.aspectRatio` | string | 否  | `1:1` / `4:3` / `3:4` / `16:9` / `9:16`     |
| `generationConfig.imageConfig.imageSize`   | string | 否  | `512` / `1K` / `2K` / `4K`（默认 `1K`）         |

<Card title="API 参考" icon="code" href="/zh/api-reference/model-api/google/gemini-3.1-flash-image">
  查看 Gemini 3.1 Flash Image 的交互式 API Playground。
</Card>

<script src="/feedback.js" />
