Gemini API 现已提供 gemini-2.5-flash-image-preview 模型(内部代号为 Nano Banana),赋予开发者强大的图片生成与处理能力。你可以通过文字、图片或两者结合的方式与 Gemini 对话,以前所未有的控制力来创建、修改和迭代视觉内容。

该模型的核心能力包括:

  • 文本生成图片 (Text-to-Image):根据简单或复杂的文本描述,生成高质量的图片。
  • 图文结合编辑 (Image + Text-to-Image):提供一张图片,并使用文本提示添加、移除或修改元素、更改风格或调整色彩。
  • 多图合成与风格迁移:使用多张输入图片合成新场景,或将一张图片的风格迁移到另一张上。
  • 对话式迭代优化:通过多轮对话逐步优化图片,进行细微调整,直至达到理想效果。
  • 高保真文本渲染:在图片中准确生成清晰易读且位置合理的文本,非常适合用于徽标、图表和海报设计。

所有通过此模型生成的图片都包含 SynthID 数字水印。

文本生成图片 (Text-to-Image)

最基础的用法是根据一段描述性文本生成图片。以下代码演示了如何实现这一功能。

提示示例:

“Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme” (在一家以 Gemini 为主题的高档餐厅里,创作一幅关于纳米香蕉菜肴的图片)

Python

from google import genai
from PIL import Image
from io import BytesIO

client = genai.Client()

prompt = (
    "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme"
)

response = client.models.generate_content(
    model="gemini-2.5-flash-image-preview",
    contents=[prompt],
)

# 处理响应并保存图片
for part in response.candidates[0].content.parts:
    if part.inline_data:
        image = Image.open(BytesIO(part.inline_data.data))
        image.save("generated_image.png")
        print("图片已保存为 generated_image.png")
    elif part.text:
        print(part.text)

JavaScript (Node.js)

import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";

async function main() {
  const ai = new GoogleGenAI(process.env.GEMINI_API_KEY);
  const prompt = "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme";

  const response = await ai.models.generateContent({
    model: "gemini-2.5-flash-image-preview",
    contents: [{ parts: [{ text: prompt }] }],
  });

  for (const part of response.candidates[0].content.parts) {
    if (part.inlineData) {
      const imageData = part.inlineData.data;
      const buffer = Buffer.from(imageData, "base64");
      fs.writeFileSync("generated_image.png", buffer);
      console.log("图片已保存为 generated_image.png");
    } else if (part.text) {
      console.log(part.text);
    }
  }
}

main();

Go

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"google.golang.org/genai"
)

func main() {
	ctx := context.Background()
	client, err := genai.NewClient(ctx, nil)
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	prompt := genai.Text("Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme")
	result, err := client.Models.GenerateContent(ctx, "gemini-2.5-flash-image-preview", prompt)
	if err != nil {
		log.Fatal(err)
	}

	for _, part := range result.Candidates[0].Content.Parts {
		if part.InlineData != nil {
			imageBytes := part.InlineData.Data
			outputFilename := "generated_image.png"
			err := os.WriteFile(outputFilename, imageBytes, 0644)
			if err != nil {
				log.Fatal(err)
			}
			fmt.Println("图片已保存为", outputFilename)
		} else if part.Text != "" {
			fmt.Println(part.Text)
		}
	}
}

REST API (cURL)

curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-image-preview:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
  "contents": [{
    "parts": [
      {"text": "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme"}
    ]
  }]
}' \
| grep -o '"data": "[^"]*"' \
| cut -d '"' -f4 \
| base64 --decode > generated_image.png

图文结合生成图片 (图片编辑)

你也可以提供一张图片和一段文本提示,让模型对现有图片进行修改或再创作。

注意:请确保您对上传的所有图片均拥有必要权利。使用此生成式 AI 服务时,须遵守相关的使用限制政策。

以下示例演示了如何上传一张 Base64 编码的图片,并结合文本提示生成新图片。

提示示例:

“Create a picture of my cat eating a nano-banana in a fancy restaurant under the Gemini constellation” (创作一张我的猫在双子座星空下的高档餐厅里吃纳米香蕉的图片)

Python

from google import genai
from PIL import Image
from io import BytesIO

client = genai.Client()

# 打开本地图片文件
image = Image.open("/path/to/your/cat_image.png")

prompt = (
    "Create a picture of my cat eating a nano-banana in a "
    "fancy restaurant under the Gemini constellation"
)

response = client.models.generate_content(
    model="gemini-2.5-flash-image-preview",
    contents=[prompt, image],
)

# 处理响应并保存图片
for part in response.candidates[0].content.parts:
    if part.inline_data:
        new_image = Image.open(BytesIO(part.inline_data.data))
        new_image.save("edited_image.png")
        print("图片已保存为 edited_image.png")
    elif part.text:
        print(part.text)

JavaScript (Node.js)

import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";

async function main() {
  const ai = new GoogleGenAI(process.env.GEMINI_API_KEY);

  const imagePath = "/path/to/your/cat_image.png";
  const imageData = fs.readFileSync(imagePath);
  const base64Image = imageData.toString("base64");

  const prompt = [
    {
      text: "Create a picture of my cat eating a nano-banana in a fancy restaurant under the Gemini constellation",
    },
    {
      inlineData: {
        mimeType: "image/png",
        data: base64Image,
      },
    },
  ];

  const response = await ai.models.generateContent({
    model: "gemini-2.5-flash-image-preview",
    contents: [{ parts: prompt }],
  });

  for (const part of response.candidates[0].content.parts) {
    if (part.inlineData) {
      const imageData = part.inlineData.data;
      const buffer = Buffer.from(imageData, "base64");
      fs.writeFileSync("edited_image.png", buffer);
      console.log("图片已保存为 edited_image.png");
    } else if (part.text) {
      console.log(part.text);
    }
  }
}

main();

Go

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"google.golang.org/genai"
)

func main() {
	ctx := context.Background()
	client, err := genai.NewClient(ctx, nil)
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	imagePath := "/path/to/your/cat_image.png"
	imgData, err := os.ReadFile(imagePath)
	if err != nil {
		log.Fatal(err)
	}

	parts := []*genai.Part{
		genai.NewPartFromText("Create a picture of my cat eating a nano-banana in a fancy restaurant under the Gemini constellation"),
		{
			InlineData: &genai.Blob{
				MIMEType: "image/png",
				Data:     imgData,
			},
		},
	}

	result, err := client.Models.GenerateContent(ctx, "gemini-2.5-flash-image-preview", parts...)
	if err != nil {
		log.Fatal(err)
	}

	for _, part := range result.Candidates[0].Content.Parts {
		if part.InlineData != nil {
			imageBytes := part.InlineData.Data
			outputFilename := "edited_image.png"
			err := os.WriteFile(outputFilename, imageBytes, 0644)
			if err != nil {
				log.Fatal(err)
			}
			fmt.Println("图片已保存为", outputFilename)
		} else if part.Text != "" {
			fmt.Println(part.Text)
		}
	}
}

REST API (cURL)

IMG_PATH="/path/to/your/cat_image.png"

# 根据操作系统选择正确的 base64 参数
if [[ "$(base64 --version 2>&1)" = *"FreeBSD"* ]]; then
  B64FLAGS="--input"
else
  B64FLAGS="-w0"
fi

IMG_BASE64=$(base64 "$B64FLAGS" "$IMG_PATH")

curl -X POST \
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-image-preview:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d @- << EOF
{
  "contents": [{
    "parts":[
      {"text": "Create a picture of my cat eating a nano-banana in a fancy restaurant under the Gemini constellation"},
      {
        "inline_data": {
          "mime_type":"image/png",
          "data": "$IMG_BASE64"
        }
      }
    ]
  }]
}
EOF

其他高级生成模式

Gemini 还支持更复杂的图片交互模式,具体取决于提示的结构和上下文:

  • 图文交错生成:根据提示,同时输出包含相关文本的图片。
    • 提示示例:“生成一份图文并茂的海鲜饭食谱。”
  • 多轮对话式图片编辑:以聊天的形式,持续对图片进行修改。
    • 对话示例
      1. (上传一张蓝色汽车的图片)
      2. 用户:“把这辆车变成敞篷车。”
      3. 用户:“现在把颜色改成黄色。”

提示词工程最佳实践

要充分发挥 Gemini 图片生成的能力,请记住一个核心原则:描述场景,而非罗列关键词

该模型的核心优势在于其深厚的语言理解能力。与一连串不相关的词语相比,一段叙事性的描述几乎总能生成更优质、更连贯的图片。

1. 生成写实照片

要生成逼真的图片,请使用摄影术语。提及拍摄角度、镜头类型、光线和细节,可以引导模型生成更具真实感的效果。

  • 模板:

    A photorealistic [shot type] of [subject], [action or expression], set in [environment]. The scene is illuminated by [lighting description], creating a [mood] atmosphere. Captured with a [camera/lens details], emphasizing [key textures and details].

    一张关于[主体]的写实[拍摄类型]照片,[主体]正在[动作或表情],场景设置在[环境]中。场景由[光线描述]照亮,营造出[氛围]的氛围。使用[相机/镜头细节]拍摄,强调了[关键纹理和细节]。

  • 提示示例:

    A photorealistic close-up portrait of an elderly Japanese ceramicist with deep, sun-etched wrinkles and a warm, knowing smile. He is carefully inspecting a freshly glazed tea bowl. The setting is his rustic, sun-drenched workshop. The scene is illuminated by soft, golden hour light streaming through a window, highlighting the fine texture of the clay. Captured with an 85mm portrait lens, resulting in a soft, blurred background (bokeh). The overall mood is serene and masterful.

    一位年迈的日本陶艺家的写实特写肖像,他脸上布满深刻的皱纹,带着温暖而会心的微笑。他正在仔细检查一个刚上釉的茶碗。背景是他那间阳光普照的乡村作坊。柔和的金色夕阳之光从窗户射入,照亮了陶土的细腻质感。使用 85mm 人像镜头拍摄,背景柔和模糊(焦外成像)。整体氛围宁静而富有大师风范。

2. 创作风格化插画与贴纸

在创建贴纸、图标或素材时,请明确说明所需的风格,并可以要求使用透明背景。

  • 模板:

    A [style] sticker of a [subject], featuring [key characteristics] and a [color palette]. The design should have [line style] and [shading style]. The background must be transparent.

    一张[风格]的[主体]贴纸,具有[关键特征]和[色调]。设计应采用[线条风格]和[阴影风格]。背景必须是透明的。

  • 提示示例:

    A kawaii-style sticker of a happy red panda wearing a tiny bamboo hat. It’s munching on a green bamboo leaf. The design features bold, clean outlines, simple cel-shading, and a vibrant color palette. The background must be white.

    一张卡哇伊风格的贴纸,画的是一只戴着小竹帽的快乐小熊猫。它正在啃一片绿色的竹叶。设计采用粗大清晰的轮廓、简约的赛璐璐风格着色和鲜艳的色调。背景必须为白色。

3. 在图片中精准渲染文字

Gemini 在渲染文本方面表现出色。在提示中清晰地说明所需文字、字体风格(可用描述性词语)和整体设计。

  • 模板:

    Create a [image type] for [brand/concept] with the text “[text to render]” in a [font style]. The design should be [style description], with a [color scheme].

    为[品牌/概念]创建一个[图片类型],其中包含文字“[要渲染的文本]”,字体为[字体风格]。设计应为[风格描述],配色方案为[配色方案]。

  • 提示示例:

    Create a modern, minimalist logo for a coffee shop called ‘The Daily Grind’. The text should be in a clean, bold, sans-serif font. The design should feature a simple, stylized icon of a coffee bean seamlessly integrated with the text. The color scheme is black and white.

    为一家名为“The Daily Grind”的咖啡店设计一个现代简约的徽标。文字应采用干净、粗体的无衬线字体。设计应包含一个与文字无缝融合的简约风格化咖啡豆图标。配色方案为黑白。


👉 如果你需要 ChatGPT 代充 / Claude / Claude Code / 镜像 / 中转 API