Nano Banana 图片生成

通过提示词,即可快速构建功能完备、界面完整的应用原型,并见证 Nano Banana 2 与实际工具、数据和 Gemini 生态系统的无缝集成。所有这些都无需编写任何代码。
  • 或者,您也可以通过提示自行构建:
  • 杂志 伦敦 恢复 香蕉 咖啡馆 冠词 狗 等距
  • 杂志
    由 Nano Banana 2 生成
    提示:“一张光面杂志封面的照片,简约的蓝色封面上印有大号粗体字‘Nano Banana’。文本采用衬线字体,并填充整个视图。不要包含任何其他文字。文字前面有一幅肖像画,画的是一个穿着时尚简约连衣裙的人。她俏皮地拿着数字 2,这是焦点。
    在角落处放置期号和“2026 年 2 月”日期,以及条形码。杂志放在设计师商店内一面橙色抹灰墙壁前的架子上。”
  • 伦敦
    由 Nano Banana Pro 生成
    提示:“呈现一个清晰的 45° 俯视角等距微缩 3D 卡通伦敦场景,其中包含伦敦最具标志性的地标和建筑元素。使用柔和、精致的纹理,搭配逼真的 PBR 材质以及柔和、逼真的光影效果。将当前天气状况直接融入城市环境,营造沉浸式氛围。采用简洁、极简的构图,搭配柔和的纯色背景。在顶部中央,用大号粗体文字显示标题“London”,下方放置一个醒目的天气图标,然后是日期(小号文字)和温度(中号文字)。所有文字都必须居中,间距一致,并且可以稍微与建筑物顶部重叠。”
  • 格查尔
    由 Nano Banana 2 生成
    提示:“使用图片搜索功能查找凤尾绿咬鹃的准确图片。为这只鸟制作一张精美的 3:2 壁纸,采用自然的自上而下渐变效果和极简构图。”
  • 香蕉
    由 Nano Banana Pro 生成
    提示:“将此徽标放在香蕉味香水的高端广告中。徽标与瓶身完美融合。”
  • 咖啡馆
    由 Nano Banana Pro 生成
    提示:“一张照片,展示一家供应早餐的繁忙咖啡馆的日常场景。前景中有一个蓝发动漫男子,其中一人是铅笔素描,另一人是黏土动画人物”
  • 冠词
    由 Nano Banana Pro 生成
    提示:“使用搜索功能,了解 Gemini 3 Flash 发布后的反响。使用这些信息撰写一篇关于该主题的简短文章(带标题)。返回一幅照片,展示该文章在设计类精美杂志中的呈现效果。这是一张折叠页面的照片,展示了有关 Gemini 3 Flash 的文章。一张主打照片。Headline in serif."
  • 狗
    由 Nano Banana Pro 生成
    提示:“一个代表可爱狗狗的图标。背景为白色。图标采用色彩丰富、触感逼真的 3D 风格。没有文字。”
  • 等距
    由 Nano Banana 2 生成
    提示:“生成一张完全等距的照片。这不是微缩模型,而是一张恰好呈现完美等距视角的实拍照片。这是一张美丽现代花园的照片。画面中有一个数字“2”形状的大型泳池,以及“Nano Banana 2”字样。

Nano Banana 是 Gemini 原生图片生成功能的名称。 Gemini 能够以对话方式生成并处理图片, 支持文本、图片、视频或其组合。您可以使用文本、图片或结合使用两者向 Gemini 发出提示 从而以前所未有的精准度创建、修改和迭代视觉内容

模型选择

Nano Banana 是指 Gemini API 中提供的以下模型:

  • Nano Banana 2.1 (Gemini Nano Banana 2.1) (gemini-nano-banana-2.1):Nano Banana 2 的更新版本,是用于图片生成和对话式编辑的主要高效主力模型。它在保持 Flash 级速度和成本效益的同时,还提升了视觉质量、文字渲染、多轮一致性,并支持在 1K、2K 和 4K 分辨率下使用 Google 搜索进行接地。
  • Nano Banana 2 Lite (Gemini 3.1 Flash Lite Image) (gemini-3.1-flash-lite-image):速度最快、价格最低的 Gemini 图片模型,专为速度和规模而设计,适用于速度和成本是主要运营限制因素的场景。未针对多个参考输入或多轮顺序编辑进行优化。
  • Nano Banana 2 (Gemini 3.1 Flash Image) (gemini-3.1-flash-image):上一代高效主力模型,在速度、4K 生成、世界知识和多参考图片一致性之间实现了平衡。建议所有新项目都使用 Nano Banana 2.1。
  • Nano Banana Pro (Gemini 3 Pro Image) (gemini-3-pro-image):处理最复杂的视觉任务的优质选择,提供最高水平的世界知识、高级本地化、准确的品牌一致性和精准的创意控制。
  • Nano Banana (Gemini 2.5 Flash Image) (gemini-2.5-flash-image):Nano Banana 系列的先驱。虽然它一直是一个可靠的主力模型,但我们建议您迁移到 Nano Banana 2 Lite,以体验更高的质量、更快的生成速度和更低的 API 价格。

生成的所有图片都包含 SynthID 水印。

图片生成(文生图)

Python

from google import genai
from PIL import Image
import base64

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input="Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme",
)

with open("generated_image.png", "wb") as f:
    f.write(base64.b64decode(interaction.output_image.data))

JavaScript

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

async function main() {

  const ai = new GoogleGenAI({});

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

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: prompt,
  });
  const generatedImage = interaction.output_image;
  if (generatedImage) {
    const buffer = Buffer.from(generatedImage.data, "base64");
    fs.writeFileSync("gemini-native-image.png", buffer);
    console.log("Image saved as gemini-native-image.png");
  }
}

main();

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

Client client = new Client();

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(
            InteractionsInput.of(
                "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme"))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

if (interaction.outputImage().isPresent()
    && interaction.outputImage().get().data().isPresent()) {
  byte[] imageBytes =
      Base64.getDecoder().decode(interaction.outputImage().get().data().get());
  Files.write(Paths.get("generated_image.png"), imageBytes);
}

Go

package main

import (
    "context"
    "encoding/base64"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

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

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-nano-banana-2.1"),
            Input: interactions.NewInteractionsInput("Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme"),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    if res.Interaction.OutputImage != nil && res.Interaction.OutputImage.Data != nil {
        imageBytes, err := base64.StdEncoding.DecodeString(*res.Interaction.OutputImage.Data)
        if err != nil {
            log.Fatal(err)
        }
        if err := os.WriteFile("generated_image.png", imageBytes, 0644); err != nil {
            log.Fatal(err)
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-nano-banana-2.1",
    "input": [
      {"type": "text", "text": "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme"}
    ]
  }'

您可以使用 interaction.output_image 属性检索生成的图片数据,该属性会返回最后生成的图片块。如需详细了解便捷属性,请参阅互动概览。

图片编辑(文本和图片转图片)

提醒:请确保您对上传的所有图片均拥有必要权利。 请勿生成会侵犯他人权利的内容,包括会欺骗、骚扰或伤害他人的视频或图片。使用此生成式 AI 服务时须遵守我们的《使用限制政策》。

提供图片并使用文本提示词来添加、移除或修改元素,更改样式或调整调色。

以下示例演示了如何上传 base64 编码的图片。 如需了解多张图片、更大的载荷和支持的 MIME 类型,请参阅图片理解页面。

Python

from google import genai
from PIL import Image
import base64

client = genai.Client()

with open("/path/to/cat_image.png", "rb") as f:
    image_bytes = f.read()

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input=[
        {
          "type": "text",
          "text": "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme"
        },
        {
            "type": "image",
            "data": base64.b64encode(image_bytes).decode('utf-8'),
            "mime_type": "image/png"
        }
    ],
)

with open("generated_image.png", "wb") as f:
    f.write(base64.b64decode(interaction.output_image.data))

JavaScript

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

async function main() {

  const ai = new GoogleGenAI({});

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

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

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: prompt,
  });
  const generatedImage = interaction.output_image;
  if (generatedImage) {
    const buffer = Buffer.from(generatedImage.data, "base64");
    fs.writeFileSync("gemini-native-image.png", buffer);
    console.log("Image saved as gemini-native-image.png");
  }
}

main();

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.ImageContent;
import com.google.genai.gaos.models.interactions.ImageContentMimeType;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;

Client client = new Client();

byte[] inputBytes = Files.readAllBytes(Paths.get("/path/to/cat_image.png"));
String base64Image = Base64.getEncoder().encodeToString(inputBytes);

Content textContent =
    TextContent.builder()
        .text("Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme")
        .build();
Content imageContent =
    ImageContent.builder()
        .data(base64Image)
        .mimeType(ImageContentMimeType.IMAGE_PNG)
        .build();

List<Content> contents = Arrays.asList(textContent, imageContent);

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(InteractionsInput.ofContent(contents))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

if (interaction.outputImage().isPresent()
    && interaction.outputImage().get().data().isPresent()) {
  byte[] outputBytes =
      Base64.getDecoder().decode(interaction.outputImage().get().data().get());
  Files.write(Paths.get("generated_image.png"), outputBytes);
}

Go

package main

import (
    "context"
    "encoding/base64"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

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

    inputBytes, err := os.ReadFile("/path/to/cat_image.png")
    if err != nil {
        log.Fatal(err)
    }
    base64Image := base64.StdEncoding.EncodeToString(inputBytes)

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-nano-banana-2.1"),
            Input: interactions.NewInteractionsInput([]interactions.Content{
                interactions.NewContent(interactions.TextContent{
                    Text: "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme",
                }),
                interactions.NewContent(interactions.ImageContent{
                    Data:     genai.Ptr(base64Image),
                    MimeType: interactions.ImageContentMimeTypeImagePng.ToPointer(),
                }),
            }),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    if res.Interaction.OutputImage != nil && res.Interaction.OutputImage.Data != nil {
        outputBytes, err := base64.StdEncoding.DecodeString(*res.Interaction.OutputImage.Data)
        if err != nil {
            log.Fatal(err)
        }
        if err := os.WriteFile("generated_image.png", outputBytes, 0644); err != nil {
            log.Fatal(err)
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
    -H "x-goog-api-key: $GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -d "{
      \"model\": \"gemini-nano-banana-2.1\",
      \"input\": [
        {\"type\": \"text\", \"text\": \"Create a picture of my cat eating a nano-banana in a fancy restaurant under the Gemini constellation\"},
        {
          \"type\": \"image\",
          \"mime_type\": \"image/jpeg\",
          \"data\": \"<BASE64_IMAGE_DATA>\"
        }
      ]
    }"

多轮图片修改

继续以对话方式生成和修改图片。建议通过多轮对话来迭代图片。以下示例展示了用于生成光合作用信息图的提示。

Python

from google import genai
import base64

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input="Create a vibrant infographic that explains photosynthesis as if it were a recipe for a plant's favorite food. Show the \"ingredients\" (sunlight, water, CO2) and the \"finished dish\" (sugar/energy). The style should be like a page from a colorful kids' cookbook, suitable for a 4th grader.",
    tools=[{"type": "google_search"}],
)

with open("photosynthesis.png", "wb") as f:
    f.write(base64.b64decode(interaction.output_image.data))

JavaScript

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

const ai = new GoogleGenAI({});

async function main() {
  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: "Create a vibrant infographic that explains photosynthesis as if it were a recipe for a plant's favorite food. Show the \"ingredients\" (sunlight, water, CO2) and the \"finished dish\" (sugar/energy). The style should be like a page from a colorful kids' cookbook, suitable for a 4th grader.",
    tools: [{"type": "google_search"}],
  });

  const generatedImage = interaction.output_image;
  if (generatedImage) {
    const buffer = Buffer.from(generatedImage.data, "base64");
    fs.writeFileSync("photosynthesis.png", buffer);
    console.log("Image saved as photosynthesis.png");
  }
}

await main();

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.GoogleSearch;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;

Client client = new Client();

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(
            InteractionsInput.of(
                "Create a vibrant infographic that explains photosynthesis as if it were a recipe for a plant's favorite food. Show the \"ingredients\" (sunlight, water, CO2) and the \"finished dish\" (sugar/energy). The style should be like a page from a colorful kids' cookbook, suitable for a 4th grader."))
        .tools(Arrays.asList(new GoogleSearch()))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

if (interaction.outputImage().isPresent()
    && interaction.outputImage().get().data().isPresent()) {
  byte[] imageBytes =
      Base64.getDecoder().decode(interaction.outputImage().get().data().get());
  Files.write(Paths.get("photosynthesis.png"), imageBytes);
}

Go

package main

import (
    "context"
    "encoding/base64"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

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

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-nano-banana-2.1"),
            Input: interactions.NewInteractionsInput(`Create a vibrant infographic that explains photosynthesis as if it were a recipe for a plant's favorite food. Show the "ingredients" (sunlight, water, CO2) and the "finished dish" (sugar/energy). The style should be like a page from a colorful kids' cookbook, suitable for a 4th grader.`),
            Tools: []interactions.Tool{
                interactions.NewTool(interactions.GoogleSearch{}),
            },
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    if res.Interaction.OutputImage != nil && res.Interaction.OutputImage.Data != nil {
        imageBytes, err := base64.StdEncoding.DecodeString(*res.Interaction.OutputImage.Data)
        if err != nil {
            log.Fatal(err)
        }
        if err := os.WriteFile("photosynthesis.png", imageBytes, 0644); err != nil {
            log.Fatal(err)
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-nano-banana-2.1",
    "input": [
      {"type": "text", "text": "Create a vibrant infographic that explains photosynthesis as if it were a recipe for a plants favorite food. Show the \"ingredients\" (sunlight, water, CO2) and the \"finished dish\" (sugar/energy). The style should be like a page from a colorful kids cookbook, suitable for a 4th grader."}
    ],
    "tools": [{"type": "google_search"}]
  }'
AI 生成的光合作用信息图
AI 生成的关于光合作用的信息图

然后,您可以使用 previous_interaction_id 将图片上的语言更改为西班牙语。

Python

interaction_2 = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input="Update this infographic to be in Spanish. Do not change any other elements of the image.",
    previous_interaction_id=interaction.id,
    response_format={
        "type": "image",
        "mime_type": "image/jpeg",
        "aspect_ratio": "16:9",
        "image_size": "2K"
    },
)

generated_image = interaction_2.output_image
if generated_image:
    with open("photosynthesis_spanish.png", "wb") as f:
        f.write(base64.b64decode(generated_image.data))

JavaScript

const interaction2 = await ai.interactions.create({
  model: "gemini-nano-banana-2.1",
  input: "Update this infographic to be in Spanish. Do not change any other elements of the image.",
  previous_interaction_id: interaction.id,
  response_format: {
    type: "image",
    mime_type: "image/png",
    aspect_ratio: "16:9",
    image_size: "2K"
  },
});

const generatedImage = interaction2.output_image;
if (generatedImage) {
  const buffer = Buffer.from(generatedImage.data, "base64");
  fs.writeFileSync("photosynthesis_spanish.png", buffer);
}

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.CreateModelInteractionResponseFormat;
import com.google.genai.gaos.models.interactions.GoogleSearch;
import com.google.genai.gaos.models.interactions.ImageResponseFormat;
import com.google.genai.gaos.models.interactions.ImageResponseFormatAspectRatio;
import com.google.genai.gaos.models.interactions.ImageResponseFormatImageSize;
import com.google.genai.gaos.models.interactions.ImageResponseFormatMimeType;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ResponseFormat;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;

Client client = new Client();

CreateModelInteraction turn1Params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(
            InteractionsInput.of(
                "Create a vibrant infographic that explains photosynthesis as if it were a recipe for a plant's favorite food."))
        .tools(Arrays.asList(new GoogleSearch()))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(turn1Params)).interaction().get();

CreateModelInteractionResponseFormat format =
    CreateModelInteractionResponseFormat.of(
        ResponseFormat.of(
            ImageResponseFormat.builder()
                .mimeType(ImageResponseFormatMimeType.IMAGE_JPEG)
                .aspectRatio(ImageResponseFormatAspectRatio.of("16:9"))
                .imageSize(ImageResponseFormatImageSize.TWO_K)
                .build()));

CreateModelInteraction turn2Params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(
            InteractionsInput.of(
                "Update this infographic to be in Spanish. Do not change any other elements of the image."))
        .previousInteractionId(interaction.id().orElse(""))
        .responseFormat(format)
        .build();

Interaction interaction2 =
    client.interactions.create(CreateInteractionRequestBody.of(turn2Params)).interaction().get();

if (interaction2.outputImage().isPresent()
    && interaction2.outputImage().get().data().isPresent()) {
  byte[] imageBytes =
      Base64.getDecoder().decode(interaction2.outputImage().get().data().get());
  Files.write(Paths.get("photosynthesis_spanish.png"), imageBytes);
}

Go

package main

import (
    "context"
    "encoding/base64"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

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

    res1, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-nano-banana-2.1"),
            Input: interactions.NewInteractionsInput("Create a vibrant infographic that explains photosynthesis as if it were a recipe for a plant's favorite food."),
            Tools: []interactions.Tool{
                interactions.NewTool(interactions.GoogleSearch{}),
            },
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    format := interactions.NewCreateModelInteractionResponseFormat(
        interactions.NewResponseFormat(interactions.ImageResponseFormat{
            MimeType:    interactions.ImageResponseFormatMimeTypeImageJpeg.ToPointer(),
            AspectRatio: interactions.ImageResponseFormatAspectRatio("16:9").ToPointer(),
            ImageSize:   interactions.ImageResponseFormatImageSizeTwoK.ToPointer(),
        }),
    )

    res2, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model:                 interactions.Model("gemini-nano-banana-2.1"),
            Input:                 interactions.NewInteractionsInput("Update this infographic to be in Spanish. Do not change any other elements of the image."),
            PreviousInteractionID: res1.Interaction.ID,
            ResponseFormat:        genai.Ptr(format),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    if res2.Interaction.OutputImage != nil && res2.Interaction.OutputImage.Data != nil {
        imageBytes, err := base64.StdEncoding.DecodeString(*res2.Interaction.OutputImage.Data)
        if err != nil {
            log.Fatal(err)
        }
        if err := os.WriteFile("photosynthesis_spanish.png", imageBytes, 0644); err != nil {
            log.Fatal(err)
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "gemini-nano-banana-2.1",
    "input": "Update this infographic to be in Spanish. Do not change any other elements of the image.",
    "previous_interaction_id": "<PREVIOUS_INTERACTION_ID>",
    "response_format": {
      "type": "image",
      "mime_type": "image/jpeg",
      "aspect_ratio": "16:9",
      "image_size": "2K"
    }
  }'
AI 生成的西班牙语光合作用信息图
AI 生成的西班牙语光合作用信息图

Nano Banana 的功能

Nano Banana 模型提供先进的图片生成和编辑功能。Gemini Nano Banana 2.1 和 Gemini 3.1 Flash Image 针对速度和高容量用例进行了优化,而 Gemini 3 Pro Image 针对专业资产制作进行了优化。这些模型旨在通过高级推理来处理最具挑战性的工作流,擅长执行复杂的多轮创建和修改任务。

  • 高分辨率输出:内置生成 1K、2K 和 4K 视觉内容的能力。
    • Gemini 3.1 Flash Image 新增了较小的 512 像素 (0.5K) 分辨率(Gemini Nano Banana 2.1 不支持)。
    • Gemini 3.1 Flash Lite Image 仅支持 1K 分辨率。
  • 高级文本呈现:能够为信息图、菜单、图表和营销资产生成清晰易读、风格化的文本。
  • 依托 Google 搜索进行接地:模型可以使用 Google 搜索作为工具,根据实时数据(例如当前天气图、股票图表、近期事件)验证事实并生成图像。
    • Gemini 3.1 Flash Lite Image 模型不支持此功能。
    • Gemini Nano Banana 2.1 和 Gemini 3.1 Flash Image 在网页搜索的基础上,新增了 Google 图片搜索接地功能。
  • 思考模式:模型利用“思考”过程来推理复杂的提示。它会生成临时“思考图片”(在后端可见,但不收费),以在生成最终的高质量输出之前优化构图。
  • 最多 14 张参考图片:最多可混合使用 14 张参考图片来生成最终图片。
  • 新增宽高比:Gemini 3.1 Flash Lite Image 新增了 1:1、3:2、2:3、3:4、4:3、4:5、5:4、9:16、16:9、21:9 宽高比。

最多可使用 14 张参考图片

Nano Banana 模型支持混合多达 14 张参考图片。这 14 张图片可以包括以下内容:

Gemini 3.1 Flash Lite Image Gemini Nano Banana 2.1 和 Gemini 3.1 Flash Image Gemini 3 Pro Image
最多 14 张高保真对象图片,用于添加到最终图片中 最多 10 张要包含在最终图片中的高保真对象图片 最多 6 张高保真对象图片,用于添加到最终图片中
不适用 最多 4 张角色图片,以保持角色一致性 最多 5 张角色图片,用于保持角色一致性
不适用 不适用 最多可使用 3 张图片作为样式参考

Python

from google import genai
from google.genai import types
from PIL import Image
import base64

prompt = "An office group photo of these people, they are making funny faces."

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input=[
        {
            "type": "text",
            "text": prompt,
        },
        {
            "type": "image",
            "data": base64.b64encode(image_bytes).decode('utf-8'),
            "mime_type": "image/png"
        },
        {
            "type": "image",
            "data": base64.b64encode(image_bytes).decode('utf-8'),
            "mime_type": "image/png"
        },
        {
            "type": "image",
            "data": base64.b64encode(image_bytes).decode('utf-8'),
            "mime_type": "image/png"
        },
        {
            "type": "image",
            "data": base64.b64encode(image_bytes).decode('utf-8'),
            "mime_type": "image/png"
        },
        {
            "type": "image",
            "data": base64.b64encode(image_bytes).decode('utf-8'),
            "mime_type": "image/png"
        },
    ],
    response_format={
        "type": "image",
        "aspect_ratio": "5:4",
        "image_size": "2K"
    },
)

with open("office.png", "wb") as f:
    f.write(base64.b64decode(interaction.output_image.data))

JavaScript

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

async function main() {
  const ai = new GoogleGenAI({});

  const input = [
    {
      type: "text",
      text: "An office group photo of these people, they are making funny faces.",
    },
    { type: "image", mime_type: "image/jpeg", data: base64ImageFile1 },
    { type: "image", mime_type: "image/jpeg", data: base64ImageFile2 },
    { type: "image", mime_type: "image/jpeg", data: base64ImageFile3 },
    { type: "image", mime_type: "image/jpeg", data: base64ImageFile4 },
    { type: "image", mime_type: "image/jpeg", data: base64ImageFile5 },
  ];

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: input,
    response_format: {
      type: "image",
      aspect_ratio: "5:4",
      image_size: "2K",
    },
  });

  const buffer = Buffer.from(interaction.output_image.data, 'base64');

  fs.writeFileSync('office.png', buffer);
}

main();

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.CreateModelInteractionResponseFormat;
import com.google.genai.gaos.models.interactions.ImageContent;
import com.google.genai.gaos.models.interactions.ImageContentMimeType;
import com.google.genai.gaos.models.interactions.ImageResponseFormat;
import com.google.genai.gaos.models.interactions.ImageResponseFormatAspectRatio;
import com.google.genai.gaos.models.interactions.ImageResponseFormatImageSize;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ResponseFormat;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;

String prompt = "An office group photo of these people, they are making funny faces.";

byte[] imageBytes = Files.readAllBytes(Paths.get("/path/to/person.png"));
String base64Image = Base64.getEncoder().encodeToString(imageBytes);

Content textContent = TextContent.builder().text(prompt).build();
Content imageContent =
    ImageContent.builder()
        .data(base64Image)
        .mimeType(ImageContentMimeType.IMAGE_PNG)
        .build();

List<Content> contents =
    Arrays.asList(
        textContent,
        imageContent,
        imageContent,
        imageContent,
        imageContent,
        imageContent);

CreateModelInteractionResponseFormat format =
    CreateModelInteractionResponseFormat.of(
        ResponseFormat.of(
            ImageResponseFormat.builder()
                .aspectRatio(ImageResponseFormatAspectRatio.of("5:4"))
                .imageSize(ImageResponseFormatImageSize.TWO_K)
                .build()));

Client client = new Client();

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(InteractionsInput.ofContent(contents))
        .responseFormat(format)
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

if (interaction.outputImage().isPresent()
    && interaction.outputImage().get().data().isPresent()) {
  byte[] outBytes =
      Base64.getDecoder().decode(interaction.outputImage().get().data().get());
  Files.write(Paths.get("office.png"), outBytes);
}

Go

package main

import (
    "context"
    "encoding/base64"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

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

    prompt := "An office group photo of these people, they are making funny faces."

    imageBytes, err := os.ReadFile("/path/to/person.png")
    if err != nil {
        log.Fatal(err)
    }
    base64Image := base64.StdEncoding.EncodeToString(imageBytes)

    textContent := interactions.NewContent(interactions.TextContent{
        Text: prompt,
    })
    imageContent := interactions.NewContent(interactions.ImageContent{
        Data:     genai.Ptr(base64Image),
        MimeType: interactions.ImageContentMimeTypeImagePng.ToPointer(),
    })

    contents := []interactions.Content{
        textContent,
        imageContent,
        imageContent,
        imageContent,
        imageContent,
        imageContent,
    }

    format := interactions.NewCreateModelInteractionResponseFormat(
        interactions.NewResponseFormat(interactions.ImageResponseFormat{
            AspectRatio: interactions.ImageResponseFormatAspectRatio("5:4").ToPointer(),
            ImageSize:   interactions.ImageResponseFormatImageSizeTwoK.ToPointer(),
        }),
    )

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model:          interactions.Model("gemini-nano-banana-2.1"),
            Input:          interactions.NewInteractionsInput(contents),
            ResponseFormat: genai.Ptr(format),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    if res.Interaction.OutputImage != nil && res.Interaction.OutputImage.Data != nil {
        outBytes, err := base64.StdEncoding.DecodeString(*res.Interaction.OutputImage.Data)
        if err != nil {
            log.Fatal(err)
        }
        if err := os.WriteFile("office.png", outBytes, 0644); err != nil {
            log.Fatal(err)
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
    -H "x-goog-api-key: $GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -d "{
      \"model\": \"gemini-nano-banana-2.1\",
      \"input\": [
        {\"type\": \"text\", \"text\": \"An office group photo of these people, they are making funny faces.\"},
        {\"type\": \"image\", \"mime_type\": \"image/png\", \"data\": \"<BASE64_DATA_IMG_1>\"},
        {\"type\": \"image\", \"mime_type\": \"image/png\", \"data\": \"<BASE64_DATA_IMG_2>\"},
        {\"type\": \"image\", \"mime_type\": \"image/png\", \"data\": \"<BASE64_DATA_IMG_3>\"},
        {\"type\": \"image\", \"mime_type\": \"image/png\", \"data\": \"<BASE64_DATA_IMG_4>\"},
        {\"type\": \"image\", \"mime_type\": \"image/png\", \"data\": \"<BASE64_DATA_IMG_5>\"}
      ],
      \"response_format\": {
        \"type\": \"image\",
        \"aspect_ratio\": \"5:4\",
        \"image_size\": \"2K\"
      }
    }"
AI 生成的办公室合照
AI 生成的办公室合照

依托 Google 搜索进行接地

使用 Google 搜索工具,根据实时信息(例如天气预报、股票图表或近期事件)生成图片。

请注意,在将“依托 Google 搜索进行接地”与图片生成功能结合使用时,基于图片的搜索结果不会传递给生成模型,并且会从回答中排除(请参阅依托 Google 图片搜索进行接地)

Python

from google import genai
from google.genai import types
import base64
prompt = "Visualize the current weather forecast for the next 5 days in San Francisco as a clean, modern weather chart. Add a visual on what I should wear each day"

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input=prompt,
    tools=[{"type": "google_search"}],
    response_format={
        "type": "image",
        "mime_type": "image/jpeg",
        "aspect_ratio": "16:9"
    },
)

with open("weather.png", "wb") as f:
    f.write(base64.b64decode(interaction.output_image.data))

JavaScript

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

async function main() {
  const ai = new GoogleGenAI({});

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: "Visualize the current weather forecast for the next 5 days in San Francisco as a clean, modern weather chart. Add a visual on what I should wear each day",
    tools: [{"type": "google_search"}],
    response_format: {
      type: "image",
      mime_type: "image/png",
      aspect_ratio: "16:9",
      image_size: "2K"
    },
  });

  const buffer = Buffer.from(interaction.output_image.data, 'base64');

  fs.writeFileSync('weather.png', buffer);
}

main();

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.CreateModelInteractionResponseFormat;
import com.google.genai.gaos.models.interactions.GoogleSearch;
import com.google.genai.gaos.models.interactions.ImageResponseFormat;
import com.google.genai.gaos.models.interactions.ImageResponseFormatAspectRatio;
import com.google.genai.gaos.models.interactions.ImageResponseFormatMimeType;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ResponseFormat;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;

String prompt =
    "Visualize the current weather forecast for the next 5 days in San Francisco as a clean, modern weather chart. Add a visual on what I should wear each day";

Client client = new Client();

CreateModelInteractionResponseFormat format =
    CreateModelInteractionResponseFormat.of(
        ResponseFormat.of(
            ImageResponseFormat.builder()
                .mimeType(ImageResponseFormatMimeType.IMAGE_JPEG)
                .aspectRatio(ImageResponseFormatAspectRatio.of("16:9"))
                .build()));

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(InteractionsInput.of(prompt))
        .tools(Arrays.asList(new GoogleSearch()))
        .responseFormat(format)
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

if (interaction.outputImage().isPresent()
    && interaction.outputImage().get().data().isPresent()) {
  byte[] imageBytes =
      Base64.getDecoder().decode(interaction.outputImage().get().data().get());
  Files.write(Paths.get("weather.png"), imageBytes);
}

Go

package main

import (
    "context"
    "encoding/base64"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

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

    prompt := "Visualize the current weather forecast for the next 5 days in San Francisco as a clean, modern weather chart. Add a visual on what I should wear each day"

    format := interactions.NewCreateModelInteractionResponseFormat(
        interactions.NewResponseFormat(interactions.ImageResponseFormat{
            MimeType:    interactions.ImageResponseFormatMimeTypeImageJpeg.ToPointer(),
            AspectRatio: interactions.ImageResponseFormatAspectRatio("16:9").ToPointer(),
        }),
    )

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-nano-banana-2.1"),
            Input: interactions.NewInteractionsInput(prompt),
            Tools: []interactions.Tool{
                interactions.NewTool(interactions.GoogleSearch{}),
            },
            ResponseFormat: genai.Ptr(format),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    if res.Interaction.OutputImage != nil && res.Interaction.OutputImage.Data != nil {
        imageBytes, err := base64.StdEncoding.DecodeString(*res.Interaction.OutputImage.Data)
        if err != nil {
            log.Fatal(err)
        }
        if err := os.WriteFile("weather.png", imageBytes, 0644); err != nil {
            log.Fatal(err)
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-nano-banana-2.1",
    "input": [
      {"type": "text", "text": "Visualize the current weather forecast for the next 5 days in San Francisco as a clean, modern weather chart. Add a visual on what I should wear each day"}
    ],
    "tools": [{"type": "google_search"}],
    "response_format": {
      "type": "image",
      "mime_type": "image/jpeg",
      "aspect_ratio": "16:9"
    }
  }'
AI 生成的旧金山五天天气图表
AI 生成的旧金山五天天气图表

回答包括 google_search_call 和 google_search_result 步骤,以及文本步骤中的内嵌 url_citation 注释:

  • google_search_result:包含 search_suggestions,这是一个 HTML 代码段,用于在界面中呈现搜索建议。
  • url_citation 注释:文本步骤中的内嵌引用,用于将回答的各个部分与其网络来源相关联。

通过“依托 Google 图片搜索进行接地”功能,模型可以使用通过 Google 图片搜索检索到的网页图片作为图片生成的视觉上下文。图片搜索是现有“依托 Google 搜索进行接地”工具中的一种新搜索类型,与标准网页搜索一起运行。

如需启用图片搜索功能,请在 API 请求中配置 google_search 工具,并在 search_types 数组中指定 image_search。图片搜索可以单独使用,也可以与网页搜索结合使用。

Python

from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input="A detailed painting of a Timareta butterfly resting on a flower",
    tools=[{
      "type": "google_search",
      "search_types": ["web_search", "image_search"]
    }]
)

JavaScript

import { GoogleGenAI } from "@google/genai";

async function main() {
  const ai = new GoogleGenAI({});

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: "A detailed painting of a Timareta butterfly resting on a flower",
    tools: [{
      "type": "google_search",
      "search_types": ["web_search", "image_search"]
    }]
  });
}

main();

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.GoogleSearch;
import com.google.genai.gaos.models.interactions.GoogleSearchSearchType;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.Arrays;

Client client = new Client();

GoogleSearch searchTool =
    GoogleSearch.builder()
        .searchTypes(
            Arrays.asList(
                GoogleSearchSearchType.WEB_SEARCH, GoogleSearchSearchType.IMAGE_SEARCH))
        .build();

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(
            InteractionsInput.of(
                "A detailed painting of a Timareta butterfly resting on a flower"))
        .tools(Arrays.asList(searchTool))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

Go

package main

import (
    "context"
    "log"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

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

    searchTool := interactions.GoogleSearch{
        SearchTypes: []interactions.GoogleSearchSearchType{
            interactions.GoogleSearchSearchTypeWebSearch,
            interactions.GoogleSearchSearchTypeImageSearch,
        },
    }

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-nano-banana-2.1"),
            Input: interactions.NewInteractionsInput("A detailed painting of a Timareta butterfly resting on a flower"),
            Tools: []interactions.Tool{
                interactions.NewTool(searchTool),
            },
        }),
    })
    if err != nil {
        log.Fatal(err)
    }
    _ = res
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-nano-banana-2.1",
    "input": "A detailed painting of a Timareta butterfly resting on a flower",
    "tools": [{"type": "google_search", "search_types": ["web_search", "image_search"]}]
  }'

显示要求

在“依托 Google 搜索进行接地”中使用图片搜索时,您必须显示 google_search_result 步骤中的 search_suggestions。服务条款中详细说明了完整的使用要求。

答案

对于使用图片搜索的有依据的回答,API 会在回答步骤中返回内嵌引用和出处元数据:

  • url_citation 注解:model_output 中文本内容块上的内嵌引用,用于将生成的内容与其来源相关联。

  • google_search_result:包含 search_suggestions,这是一个用于在界面中呈现搜索建议的 HTML 代码段。

视频到图片生成(Nano Banana 2.1、3.1 Flash 和 3.1 Flash Lite)

视频到图片生成功能可让您使用视频的上下文作为多模态参考来生成新图片。这对于制作高质量视频缩略图、电影海报、摘要信息图或受视频场景启发的新艺术作品非常有用。

在生成过程中,模型会分析视频帧的上下文,提取视觉主题和关键事件,然后结合文本提示词合成输出图片。

您可以直接在 API 请求中传递公开 YouTube 网址,也可以使用 Files API 上传本地视频文件。

Python

from google import genai
from google.genai import types
import base64

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input=[
        {
            "type": "video",
            "uri": "https://www.youtube.com/watch?v=UTdfxFyOQTI",
            "mime_type": "video/mp4"
        },
        {"type": "text", "text": "Generate a poster image that captures the key themes of this video."}
    ],
    response_format={"type": "image", "aspect_ratio": "16:9"}
)

# Save the generated image part
for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text":
                print(content_block.text)
            elif content_block.type == "image":
                with open("video_poster.png", "wb") as f:
                    f.write(base64.b64decode(content_block.data))
                print("Image saved as video_poster.png")

JavaScript

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

async function main() {
  const ai = new GoogleGenAI({});

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: [
      {
        type: "video",
        uri: "https://www.youtube.com/watch?v=UTdfxFyOQTI",
        mime_type: "video/mp4"
      },
      { type: "text", text: "Generate a poster image that captures the key themes of this video." }
    ],
    response_format: {
      type: "image",
      aspect_ratio: "16:9"
    }
  });

  for (const step of interaction.steps) {
    if (step.type === "model_output") {
      for (const contentBlock of step.content) {
        if (contentBlock.type === "text") {
          console.log(contentBlock.text);
        } else if (contentBlock.type === "image") {
          const buffer = Buffer.from(contentBlock.data, "base64");
          fs.writeFileSync("video_poster.png", buffer);
          console.log("Image saved as video_poster.png");
        }
      }
    }
  }
}

main();

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.CreateModelInteractionResponseFormat;
import com.google.genai.gaos.models.interactions.ImageContent;
import com.google.genai.gaos.models.interactions.ImageResponseFormat;
import com.google.genai.gaos.models.interactions.ImageResponseFormatAspectRatio;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ModelOutputStep;
import com.google.genai.gaos.models.interactions.ResponseFormat;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.interactions.VideoContent;
import com.google.genai.gaos.models.interactions.VideoContentMimeType;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;

Client client = new Client();

Content videoContent =
    VideoContent.builder()
        .uri("https://www.youtube.com/watch?v=UTdfxFyOQTI")
        .mimeType(VideoContentMimeType.VIDEO_MP4)
        .build();
Content textContent =
    TextContent.builder()
        .text("Generate a poster image that captures the key themes of this video.")
        .build();

List<Content> contents = Arrays.asList(videoContent, textContent);

CreateModelInteractionResponseFormat format =
    CreateModelInteractionResponseFormat.of(
        ResponseFormat.of(
            ImageResponseFormat.builder()
                .aspectRatio(ImageResponseFormatAspectRatio.of("16:9"))
                .build()));

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(InteractionsInput.ofContent(contents))
        .responseFormat(format)
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

if (interaction.steps().isPresent()) {
  for (Step step : interaction.steps().get()) {
    if (step instanceof ModelOutputStep) {
      ModelOutputStep outputStep = (ModelOutputStep) step;
      if (outputStep.content().isPresent()) {
        for (Content block : outputStep.content().get()) {
          if (block instanceof TextContent) {
            System.out.println(((TextContent) block).text().orElse(""));
          } else if (block instanceof ImageContent) {
            ImageContent img = (ImageContent) block;
            if (img.data().isPresent()) {
              byte[] imgBytes = Base64.getDecoder().decode(img.data().get());
              Files.write(Paths.get("video_poster.png"), imgBytes);
              System.out.println("Image saved as video_poster.png");
            }
          }
        }
      }
    }
  }
}

Go

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

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

    contents := []interactions.Content{
        interactions.NewContent(interactions.VideoContent{
            URI:      genai.Ptr("https://www.youtube.com/watch?v=UTdfxFyOQTI"),
            MimeType: interactions.VideoContentMimeTypeVideoMp4.ToPointer(),
        }),
        interactions.NewContent(interactions.TextContent{
            Text: "Generate a poster image that captures the key themes of this video.",
        }),
    }

    format := interactions.NewCreateModelInteractionResponseFormat(
        interactions.NewResponseFormat(interactions.ImageResponseFormat{
            AspectRatio: interactions.ImageResponseFormatAspectRatio("16:9").ToPointer(),
        }),
    )

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model:          interactions.Model("gemini-nano-banana-2.1"),
            Input:          interactions.NewInteractionsInput(contents),
            ResponseFormat: genai.Ptr(format),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    for _, step := range res.Interaction.Steps {
        if step.ModelOutputStep != nil {
            for _, block := range step.ModelOutputStep.Content {
                if block.TextContent != nil {
                    fmt.Println(block.TextContent.Text)
                } else if block.ImageContent != nil && block.ImageContent.Data != nil {
                    imgBytes, err := base64.StdEncoding.DecodeString(*block.ImageContent.Data)
                    if err != nil {
                        log.Fatal(err)
                    }
                    if err := os.WriteFile("video_poster.png", imgBytes, 0644); err != nil {
                        log.Fatal(err)
                    }
                    fmt.Println("Image saved as video_poster.png")
                }
            }
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "gemini-nano-banana-2.1",
    "input": [
      {
        "type": "video",
        "uri": "https://www.youtube.com/watch?v=UTdfxFyOQTI",
        "mime_type": "video/mp4"
      },
      {
        "type": "text",
        "text": "Generate a poster image that captures the key themes of this video."
      }
    ],
    "response_format": {
      "type": "image",
      "aspect_ratio": "16:9"
    }
  }'
根据 YouTube 视频生成的 AI 信息图
根据 YouTube 视频生成的 AI 信息图

生成分辨率最高可达 4K 的图片

Gemini 3 图片模型默认生成 1K 图片,但也可以输出 2K、4K 和 512 像素 (0.5K)(仅限 Gemini 3.1 Flash Image)图片。如需生成分辨率更高的素材资源,请在 response_format 中指定 image_size。

您必须使用大写字母“K”(例如 512px (05.K)、1K、2K、4K)。小写参数(例如 1k)将被拒绝。

Python

from google import genai
from google.genai import types
import base64

prompt = "Da Vinci style anatomical sketch of a dissected Monarch butterfly. Detailed drawings of the head, wings, and legs on textured parchment with notes in English."

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input=prompt,
    response_format={
        "type": "image",
        "mime_type": "image/jpeg",
        "aspect_ratio": "1:1",
        "image_size": "1K"
    },
)

print(interaction.output_text)

with open("butterfly.png", "wb") as f:
    f.write(base64.b64decode(interaction.output_image.data))

JavaScript

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

async function main() {
  const ai = new GoogleGenAI({});

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: "Da Vinci style anatomical sketch of a dissected Monarch butterfly. Detailed drawings of the head, wings, and legs on textured parchment with notes in English.",
    response_format: {
      type: "image",
      mime_type: "image/png",
      aspect_ratio: "1:1",
      image_size: "1K",
    },
  });

  console.log(interaction.output_text);

  const buffer = Buffer.from(interaction.output_image.data, 'base64');

  fs.writeFileSync('butterfly.png', buffer);
}

main();

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.CreateModelInteractionResponseFormat;
import com.google.genai.gaos.models.interactions.ImageResponseFormat;
import com.google.genai.gaos.models.interactions.ImageResponseFormatAspectRatio;
import com.google.genai.gaos.models.interactions.ImageResponseFormatImageSize;
import com.google.genai.gaos.models.interactions.ImageResponseFormatMimeType;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ResponseFormat;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

String prompt =
    "Da Vinci style anatomical sketch of a dissected Monarch butterfly. Detailed drawings of the head, wings, and legs on textured parchment with notes in English.";

Client client = new Client();

CreateModelInteractionResponseFormat format =
    CreateModelInteractionResponseFormat.of(
        ResponseFormat.of(
            ImageResponseFormat.builder()
                .mimeType(ImageResponseFormatMimeType.IMAGE_JPEG)
                .aspectRatio(ImageResponseFormatAspectRatio.of("1:1"))
                .imageSize(ImageResponseFormatImageSize.ONE_K)
                .build()));

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(InteractionsInput.of(prompt))
        .responseFormat(format)
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

System.out.println(interaction.outputText().orElse(""));

if (interaction.outputImage().isPresent()
    && interaction.outputImage().get().data().isPresent()) {
  byte[] imageBytes =
      Base64.getDecoder().decode(interaction.outputImage().get().data().get());
  Files.write(Paths.get("butterfly.png"), imageBytes);
}

Go

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

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

    prompt := "Da Vinci style anatomical sketch of a dissected Monarch butterfly. Detailed drawings of the head, wings, and legs on textured parchment with notes in English."

    format := interactions.NewCreateModelInteractionResponseFormat(
        interactions.NewResponseFormat(interactions.ImageResponseFormat{
            MimeType:    interactions.ImageResponseFormatMimeTypeImageJpeg.ToPointer(),
            AspectRatio: interactions.ImageResponseFormatAspectRatio("1:1").ToPointer(),
            ImageSize:   interactions.ImageResponseFormatImageSizeOneK.ToPointer(),
        }),
    )

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model:          interactions.Model("gemini-nano-banana-2.1"),
            Input:          interactions.NewInteractionsInput(prompt),
            ResponseFormat: genai.Ptr(format),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    if res.Interaction.OutputText != nil {
        fmt.Println(*res.Interaction.OutputText)
    }

    if res.Interaction.OutputImage != nil && res.Interaction.OutputImage.Data != nil {
        imageBytes, err := base64.StdEncoding.DecodeString(*res.Interaction.OutputImage.Data)
        if err != nil {
            log.Fatal(err)
        }
        if err := os.WriteFile("butterfly.png", imageBytes, 0644); err != nil {
            log.Fatal(err)
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-nano-banana-2.1",
    "input": "Da Vinci style anatomical sketch of a dissected Monarch butterfly. Detailed drawings of the head, wings, and legs on textured parchment with notes in English.",
    "response_format": {
      "type": "image",
      "mime_type": "image/jpeg",
      "aspect_ratio": "1:1",
      "image_size": "1K"
    }
  }'

以下是根据此提示生成的示例图片:

AI 生成的达芬奇风格的黑脉金斑蝶解剖草图。
AI 生成的达芬奇风格君主斑蝶解剖图。

思考过程

Gemini 3 图片模型是思考模型,可针对复杂的提示使用推理过程(“思考”)。此功能默认处于启用状态,无法在 API 中停用。如需详细了解思考过程,请参阅 Gemini 思考指南。

模型最多会生成两张临时图片,以测试构图和逻辑。“思考”中的最后一张图片也是最终渲染的图片。

您可以查看生成最终图片的思考过程。

Python

for step in interaction.steps:
    if step.type == "thought":
        for content_block in step.summary:
            if content_block.type == "text":
                print(content_block.text)
            elif content_block.type == "image":
                image = Image.open(io.BytesIO(base64.b64decode(content_block.data)))
                image.show()

JavaScript

for (const step of interaction.steps) {
  if (step.type === "thought") {
    for (const contentBlock of step.summary) {
      if (contentBlock.type === "text") {
        console.log(contentBlock.text);
      } else if (contentBlock.type === "image") {
        const buffer = Buffer.from(contentBlock.data, 'base64');
        fs.writeFileSync('thought_image.png', buffer);
      }
    }
  }
}

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.ImageContent;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.interactions.ThoughtStep;
import com.google.genai.gaos.models.interactions.ThoughtSummaryContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

Client client = new Client();

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(
            InteractionsInput.of(
                "A futuristic city built inside a giant glass bottle floating in space"))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

if (interaction.steps().isPresent()) {
  for (Step step : interaction.steps().get()) {
    if (step instanceof ThoughtStep) {
      ThoughtStep thoughtStep = (ThoughtStep) step;
      if (thoughtStep.summary().isPresent()) {
        for (ThoughtSummaryContent contentBlock : thoughtStep.summary().get()) {
          if (contentBlock instanceof TextContent) {
            System.out.println(((TextContent) contentBlock).text().orElse(""));
          } else if (contentBlock instanceof ImageContent) {
            ImageContent img = (ImageContent) contentBlock;
            if (img.data().isPresent()) {
              byte[] imgBytes = Base64.getDecoder().decode(img.data().get());
              Files.write(Paths.get("thought_image.png"), imgBytes);
            }
          }
        }
      }
    }
  }
}

Go

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

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

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-nano-banana-2.1"),
            Input: interactions.NewInteractionsInput("A futuristic city built inside a giant glass bottle floating in space"),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    for _, step := range res.Interaction.Steps {
        if step.ThoughtStep != nil {
            for _, contentBlock := range step.ThoughtStep.Summary {
                if contentBlock.TextContent != nil {
                    fmt.Println(contentBlock.TextContent.Text)
                } else if contentBlock.ImageContent != nil && contentBlock.ImageContent.Data != nil {
                    imgBytes, err := base64.StdEncoding.DecodeString(*contentBlock.ImageContent.Data)
                    if err != nil {
                        log.Fatal(err)
                    }
                    if err := os.WriteFile("thought_image.png", imgBytes, 0644); err != nil {
                        log.Fatal(err)
                    }
                }
            }
        }
    }
}

交织的文本和图片

标准图片生成模型只能输出图片,而一些高级 Gemini 3 模型(例如 gemini-3-pro-image)可以生成交错内容,例如在同一回答中包含文本块和插图的故事或操作指南。

由于输出复杂且交错,.output_image 或 .output_text 等便捷属性无法捕获完整序列。如需访问和保存交错内容,您必须手动迭代 steps:

Python

interaction = client.interactions.create(
    model="gemini-3-pro-image",
    input="Write the story of the lifecycle of a monarch butterfly, interleave illustrations",
)

image_counter = 1
for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text":
                print(content_block.text)
            elif content_block.type == "image":
                filename = f"butterfly_lifecycle_{image_counter}.png"
                with open(filename, "wb") as f:
                    f.write(base64.b64decode(content_block.data))
                print(f"\n[Saved illustration: {filename}]\n")
                image_counter += 1

JavaScript

const interaction = await ai.interactions.create({
    model: "gemini-3-pro-image",
    input: "Write the story of the lifecycle of a monarch butterfly, interleave illustrations",
});

let imageCounter = 1;
for (const step of interaction.steps) {
  if (step.type === "model_output") {
    for (const contentBlock of step.content) {
      if (contentBlock.type === "text") {
        console.log(contentBlock.text);
      } else if (contentBlock.type === "image") {
        const buffer = Buffer.from(contentBlock.data, "base64");
        const filename = `butterfly_lifecycle_${imageCounter}.png`;
        fs.writeFileSync(filename, buffer);
        console.log(`\n[Saved illustration: ${filename}]\n`);
        imageCounter++;
      }
    }
  }
}

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.ImageContent;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ModelOutputStep;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

Client client = new Client();

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-3-pro-image"))
        .input(
            InteractionsInput.of(
                "Write the story of the lifecycle of a monarch butterfly, interleave illustrations"))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

int imageCounter = 1;
if (interaction.steps().isPresent()) {
  for (Step step : interaction.steps().get()) {
    if (step instanceof ModelOutputStep) {
      ModelOutputStep outputStep = (ModelOutputStep) step;
      if (outputStep.content().isPresent()) {
        for (Content contentBlock : outputStep.content().get()) {
          if (contentBlock instanceof TextContent) {
            System.out.println(((TextContent) contentBlock).text().orElse(""));
          } else if (contentBlock instanceof ImageContent) {
            ImageContent img = (ImageContent) contentBlock;
            if (img.data().isPresent()) {
              String filename = String.format("butterfly_lifecycle_%d.png", imageCounter);
              byte[] imgBytes = Base64.getDecoder().decode(img.data().get());
              Files.write(Paths.get(filename), imgBytes);
              System.out.printf("%n[Saved illustration: %s]%n", filename);
              imageCounter++;
            }
          }
        }
      }
    }
  }
}

Go

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

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

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-3-pro-image"),
            Input: interactions.NewInteractionsInput("Write the story of the lifecycle of a monarch butterfly, interleave illustrations"),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    imageCounter := 1
    for _, step := range res.Interaction.Steps {
        if step.ModelOutputStep != nil {
            for _, contentBlock := range step.ModelOutputStep.Content {
                if contentBlock.TextContent != nil {
                    fmt.Println(contentBlock.TextContent.Text)
                } else if contentBlock.ImageContent != nil && contentBlock.ImageContent.Data != nil {
                    filename := fmt.Sprintf("butterfly_lifecycle_%d.png", imageCounter)
                    imgBytes, err := base64.StdEncoding.DecodeString(*contentBlock.ImageContent.Data)
                    if err != nil {
                        log.Fatal(err)
                    }
                    if err := os.WriteFile(filename, imgBytes, 0644); err != nil {
                        log.Fatal(err)
                    }
                    fmt.Printf("\n[Saved illustration: %s]\n", filename)
                    imageCounter++
                }
            }
        }
    }
}

控制思考级别

借助 Gemini Nano Banana 2.1、Gemini 3.1 Flash Image 和 Gemini 3.1 Flash Lite Image,您可以控制模型使用的思考量,以平衡质量和延迟时间:

模型 支持的思考等级 默认
Gemini Nano Banana 2.1 minimal、medium、high medium
Gemini 3.1 Flash Image minimal、high minimal
Gemini 3.1 Flash Lite Image minimal、high minimal

Python

from google import genai
from PIL import Image
import base64
import io

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input="A futuristic city built inside a giant glass bottle floating in space",
    generation_config={"thinking_level": "high"},
)

print(interaction.output_text)

image = Image.open(io.BytesIO(base64.b64decode(interaction.output_image.data)))

image.show()

JavaScript

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

async function main() {
  const ai = new GoogleGenAI({});

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: "A futuristic city built inside a giant glass bottle floating in space",
    generation_config: { thinking_level: "high" },
  });

  console.log(interaction.output_text);

  const buffer = Buffer.from(interaction.output_image.data, 'base64');

  fs.writeFileSync('image.png', buffer);
}
main();

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.GenerationConfig;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ThinkingLevel;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

Client client = new Client();

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(
            InteractionsInput.of(
                "A futuristic city built inside a giant glass bottle floating in space"))
        .generationConfig(GenerationConfig.builder().thinkingLevel(ThinkingLevel.HIGH).build())
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

System.out.println(interaction.outputText().orElse(""));

if (interaction.outputImage().isPresent()
    && interaction.outputImage().get().data().isPresent()) {
  byte[] imageBytes =
      Base64.getDecoder().decode(interaction.outputImage().get().data().get());
  Files.write(Paths.get("futuristic_city.png"), imageBytes);
}

Go

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

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

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-nano-banana-2.1"),
            Input: interactions.NewInteractionsInput("A futuristic city built inside a giant glass bottle floating in space"),
            GenerationConfig: &interactions.GenerationConfig{
                ThinkingLevel: interactions.ThinkingLevelHigh.ToPointer(),
            },
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    if res.Interaction.OutputText != nil {
        fmt.Println(*res.Interaction.OutputText)
    }

    if res.Interaction.OutputImage != nil && res.Interaction.OutputImage.Data != nil {
        imageBytes, err := base64.StdEncoding.DecodeString(*res.Interaction.OutputImage.Data)
        if err != nil {
            log.Fatal(err)
        }
        if err := os.WriteFile("futuristic_city.png", imageBytes, 0644); err != nil {
            log.Fatal(err)
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-nano-banana-2.1",
    "input": "A futuristic city built inside a giant glass bottle floating in space",
    "generation_config": {
      "thinking_level": "high"
    }
  }'

请注意,默认情况下,思考模型会按思考 token 计费,因为无论您是否查看思考过程,思考过程始终默认发生。

其他图片生成模式

虽然 Nano Banana 图片生成模型适用于大多数应用场景,但您也可以探索专用图片生成模型:

  • Imagen:Google 的旧版文生图模型(已停用)。
  • Veo:Google 的视频生成模型。

批量生成图片

本页介绍的所有图片生成功能也可以使用 Batch API 作为批量作业运行,如果您需要生成许多图片,则此功能非常适合。您会获得更高的速率限制,但周转时间最长可达 24 小时。

提示指南和策略

本部分提供了常见图片生成和编辑工作流的提示示例和模板。每个示例都包含一个可重复使用的模板和 Interactions API 的示例提示。

用于生成图片的提示

以下示例展示了如何使用文本提示词生成各种类型的图片。

1. 逼真场景

详细描述一个场景。描述越具体,您对结果的控制力就越强。

模板

A photorealistic [type of shot] of a [subject description] in a [setting
description]. [Description of the light]. Shot from a [camera angle]
with a [lens type].

提示

A photorealistic wide-angle shot of a vibrant coral reef teeming with tropical fish. Crystal-clear turquoise water with sunbeams filtering down from the surface, illuminating a sea turtle gliding gracefully over the coral. Shot from a low perspective with a wide-angle lens. Aspect ratio 16:9.

Python

from google import genai
from google.genai import types
import base64

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input="A photorealistic wide-angle shot of a vibrant coral reef teeming with tropical fish. Crystal-clear turquoise water with sunbeams filtering down from the surface, illuminating a sea turtle gliding gracefully over the coral. Shot from a low perspective with a wide-angle lens. Aspect ratio 16:9.",
    response_format=[
        {
            "type": "image",
            "mime_type": "image/jpeg",
            "aspect_ratio": "16:9",
        }
    ],
)

print(interaction.output_text)

with open("coral_reef.png", "wb") as f:

    f.write(base64.b64decode(interaction.output_image.data))

JavaScript

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

async function main() {
  const ai = new GoogleGenAI({});

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: "A photorealistic wide-angle shot of a vibrant coral reef teeming with tropical fish. Crystal-clear turquoise water with sunbeams filtering down from the surface, illuminating a sea turtle gliding gracefully over the coral. Shot from a low perspective with a wide-angle lens. Aspect ratio 16:9.",
    response_format: [
      {
        type: "image",
        mime_type: "image/jpeg",
        aspect_ratio: "16:9",
      }
    ],
  });
  console.log(interaction.output_text);

  const buffer = Buffer.from(interaction.output_image.data, 'base64');

  fs.writeFileSync('coral_reef.png', buffer);
}

main();

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.CreateModelInteractionResponseFormat;
import com.google.genai.gaos.models.interactions.ImageResponseFormat;
import com.google.genai.gaos.models.interactions.ImageResponseFormatAspectRatio;
import com.google.genai.gaos.models.interactions.ImageResponseFormatMimeType;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ResponseFormat;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;

Client client = new Client();

CreateModelInteractionResponseFormat format =
    CreateModelInteractionResponseFormat.of(
        Arrays.asList(
            ResponseFormat.of(
                ImageResponseFormat.builder()
                    .mimeType(ImageResponseFormatMimeType.IMAGE_JPEG)
                    .aspectRatio(ImageResponseFormatAspectRatio.of("16:9"))
                    .build())));

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(
            InteractionsInput.of(
                "A photorealistic wide-angle shot of a vibrant coral reef teeming with tropical fish. Crystal-clear turquoise water with sunbeams filtering down from the surface, illuminating a sea turtle gliding gracefully over the coral. Shot from a low perspective with a wide-angle lens. Aspect ratio 16:9."))
        .responseFormat(format)
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

System.out.println(interaction.outputText().orElse(""));

if (interaction.outputImage().isPresent()
    && interaction.outputImage().get().data().isPresent()) {
  byte[] imageBytes =
      Base64.getDecoder().decode(interaction.outputImage().get().data().get());
  Files.write(Paths.get("coral_reef.png"), imageBytes);
}

Go

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

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

    format := interactions.NewCreateModelInteractionResponseFormat([]interactions.ResponseFormat{
        interactions.NewResponseFormat(interactions.ImageResponseFormat{
            MimeType:    interactions.ImageResponseFormatMimeTypeImageJpeg.ToPointer(),
            AspectRatio: interactions.ImageResponseFormatAspectRatio("16:9").ToPointer(),
        }),
    })

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model:          interactions.Model("gemini-nano-banana-2.1"),
            Input:          interactions.NewInteractionsInput("A photorealistic wide-angle shot of a vibrant coral reef teeming with tropical fish. Crystal-clear turquoise water with sunbeams filtering down from the surface, illuminating a sea turtle gliding gracefully over the coral. Shot from a low perspective with a wide-angle lens. Aspect ratio 16:9."),
            ResponseFormat: genai.Ptr(format),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    if res.Interaction.OutputText != nil {
        fmt.Println(*res.Interaction.OutputText)
    }

    if res.Interaction.OutputImage != nil && res.Interaction.OutputImage.Data != nil {
        imageBytes, err := base64.StdEncoding.DecodeString(*res.Interaction.OutputImage.Data)
        if err != nil {
            log.Fatal(err)
        }
        if err := os.WriteFile("coral_reef.png", imageBytes, 0644); err != nil {
            log.Fatal(err)
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-nano-banana-2.1",
    "input": "A photorealistic wide-angle shot of a vibrant coral reef teeming with tropical fish. Crystal-clear turquoise water with sunbeams filtering down from the surface, illuminating a sea turtle gliding gracefully over the coral. Shot from a low perspective with a wide-angle lens. Aspect ratio 16:9.",
    "response_format": {
      "type": "image",
      "mime_type": "image/png",
      "aspect_ratio": "16:9"
    }
  }'

2. 风格化插图和贴纸

描述艺术风格、主题和媒介。具体说明视觉细节(粗线条、颜色等),以确保结果一致。

模板

A [style] of a [subject, with details about accessories or actions]
doing [activity]. The design features [visual qualities, e.g., bold outlines,
cel-shading, etc.] and [color/background preference].

提示

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.

Python

from google import genai
import base64

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input="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.",
)

for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text":
                print(content_block.text)
            elif content_block.type == "image":
                with open("red_panda_sticker.png", "wb") as f:
                    f.write(base64.b64decode(content_block.data))

JavaScript

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

async function main() {
  const ai = new GoogleGenAI({});

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: "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.",
  });
  for (const step of interaction.steps) {
    if (step.type === "model_output") {
      for (const contentBlock of step.content) {
        if (contentBlock.type === "text") {
          console.log(contentBlock.text);
        } else if (contentBlock.type === "image") {
          const buffer = Buffer.from(contentBlock.data, "base64");
          fs.writeFileSync("red_panda_sticker.png", buffer);
        }
      }
    }
  }
}

main();

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.ImageContent;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ModelOutputStep;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

Client client = new Client();

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(
            InteractionsInput.of(
                "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."))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

if (interaction.steps().isPresent()) {
  for (Step step : interaction.steps().get()) {
    if (step instanceof ModelOutputStep) {
      ModelOutputStep outputStep = (ModelOutputStep) step;
      if (outputStep.content().isPresent()) {
        for (Content contentBlock : outputStep.content().get()) {
          if (contentBlock instanceof TextContent) {
            System.out.println(((TextContent) contentBlock).text().orElse(""));
          } else if (contentBlock instanceof ImageContent) {
            ImageContent img = (ImageContent) contentBlock;
            if (img.data().isPresent()) {
              byte[] imgBytes = Base64.getDecoder().decode(img.data().get());
              Files.write(Paths.get("red_panda_sticker.png"), imgBytes);
            }
          }
        }
      }
    }
  }
}

Go

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

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

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-nano-banana-2.1"),
            Input: interactions.NewInteractionsInput("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."),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    for _, step := range res.Interaction.Steps {
        if step.ModelOutputStep != nil {
            for _, contentBlock := range step.ModelOutputStep.Content {
                if contentBlock.TextContent != nil {
                    fmt.Println(contentBlock.TextContent.Text)
                } else if contentBlock.ImageContent != nil && contentBlock.ImageContent.Data != nil {
                    imgBytes, err := base64.StdEncoding.DecodeString(*contentBlock.ImageContent.Data)
                    if err != nil {
                        log.Fatal(err)
                    }
                    if err := os.WriteFile("red_panda_sticker.png", imgBytes, 0644); err != nil {
                        log.Fatal(err)
                    }
                }
            }
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-nano-banana-2.1",
    "input": "A kawaii-style sticker of a happy red panda wearing a tiny bamboo hat. It is 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."
  }'
一张可爱风格的贴纸,上面有一只快乐的红色…
A kawaii-style sticker of a happy red panda…

3. 图片中的文字准确

Gemini 擅长渲染文字。清楚说明文字、字体样式(描述性)和整体设计。使用 Gemini 3 Pro Image 制作专业素材资源。

模板

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 color scheme is black and white. Put the logo in a circle. Use a coffee bean in a clever way.

Python

from google import genai
import base64

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input="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 color scheme is black and white. Put the logo in a circle. Use a coffee bean in a clever way.",
    response_format={"type": "image", "aspect_ratio": "1:1"},
)

for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text":
                print(content_block.text)
            elif content_block.type == "image":
                with open("logo_example.jpg", "wb") as f:
                    f.write(base64.b64decode(content_block.data))

JavaScript

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

async function main() {
  const ai = new GoogleGenAI({});

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: "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 color scheme is black and white. Put the logo in a circle. Use a coffee bean in a clever way.",
    response_format: { type: "image", aspect_ratio: "1:1" },
  });
  for (const step of interaction.steps) {
    if (step.type === "model_output") {
      for (const contentBlock of step.content) {
        if (contentBlock.type === "text") {
          console.log(contentBlock.text);
        } else if (contentBlock.type === "image") {
          const buffer = Buffer.from(contentBlock.data, "base64");
          fs.writeFileSync("logo_example.jpg", buffer);
        }
      }
    }
  }
}

main();

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.CreateModelInteractionResponseFormat;
import com.google.genai.gaos.models.interactions.ImageContent;
import com.google.genai.gaos.models.interactions.ImageResponseFormat;
import com.google.genai.gaos.models.interactions.ImageResponseFormatAspectRatio;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ModelOutputStep;
import com.google.genai.gaos.models.interactions.ResponseFormat;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

Client client = new Client();

CreateModelInteractionResponseFormat format =
    CreateModelInteractionResponseFormat.of(
        ResponseFormat.of(
            ImageResponseFormat.builder()
                .aspectRatio(ImageResponseFormatAspectRatio.of("1:1"))
                .build()));

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(
            InteractionsInput.of(
                "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 color scheme is black and white. Put the logo in a circle. Use a coffee bean in a clever way."))
        .responseFormat(format)
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

if (interaction.steps().isPresent()) {
  for (Step step : interaction.steps().get()) {
    if (step instanceof ModelOutputStep) {
      ModelOutputStep outputStep = (ModelOutputStep) step;
      if (outputStep.content().isPresent()) {
        for (Content contentBlock : outputStep.content().get()) {
          if (contentBlock instanceof TextContent) {
            System.out.println(((TextContent) contentBlock).text().orElse(""));
          } else if (contentBlock instanceof ImageContent) {
            ImageContent img = (ImageContent) contentBlock;
            if (img.data().isPresent()) {
              byte[] imgBytes = Base64.getDecoder().decode(img.data().get());
              Files.write(Paths.get("logo_example.jpg"), imgBytes);
            }
          }
        }
      }
    }
  }
}

Go

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

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

    format := interactions.NewCreateModelInteractionResponseFormat(
        interactions.NewResponseFormat(interactions.ImageResponseFormat{
            AspectRatio: interactions.ImageResponseFormatAspectRatio("1:1").ToPointer(),
        }),
    )

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model:          interactions.Model("gemini-nano-banana-2.1"),
            Input:          interactions.NewInteractionsInput("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 color scheme is black and white. Put the logo in a circle. Use a coffee bean in a clever way."),
            ResponseFormat: genai.Ptr(format),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    for _, step := range res.Interaction.Steps {
        if step.ModelOutputStep != nil {
            for _, contentBlock := range step.ModelOutputStep.Content {
                if contentBlock.TextContent != nil {
                    fmt.Println(contentBlock.TextContent.Text)
                } else if contentBlock.ImageContent != nil && contentBlock.ImageContent.Data != nil {
                    imgBytes, err := base64.StdEncoding.DecodeString(*contentBlock.ImageContent.Data)
                    if err != nil {
                        log.Fatal(err)
                    }
                    if err := os.WriteFile("logo_example.jpg", imgBytes, 0644); err != nil {
                        log.Fatal(err)
                    }
                }
            }
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-nano-banana-2.1",
    "input": "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 color scheme is black and white. Put the logo in a circle. Use a coffee bean in a clever way.",
    "response_format": {
      "type": "image",
      "aspect_ratio": "1:1"
    }
  }'
为名为“The Daily Grind”的咖啡店设计一个现代、简约的徽标…
为名为“The Daily Grind”的咖啡馆设计一个现代、简约的徽标…

4. 商品视觉稿和商业摄影

非常适合为电子商务、广告或品牌推广制作干净、专业的产品照片。

模板

A high-resolution, studio-lit product photograph of a [product description]
on a [background surface/description]. The lighting is a [lighting setup,
e.g., three-point softbox setup] to [lighting purpose]. The camera angle is
a [angle type] to showcase [specific feature]. Ultra-realistic, with sharp
focus on [key detail]. [Aspect ratio].

提示

A high-resolution, studio-lit product photograph of a minimalist ceramic
coffee mug in matte black, presented on a polished concrete surface. The
lighting is a three-point softbox setup designed to create soft, diffused
highlights and eliminate harsh shadows. The camera angle is a slightly
elevated 45-degree shot to showcase its clean lines. Ultra-realistic, with
sharp focus on the steam rising from the coffee. Square image.

Python

from google import genai
import base64

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input="A high-resolution, studio-lit product photograph of a minimalist ceramic coffee mug in matte black, presented on a polished concrete surface. The lighting is a three-point softbox setup designed to create soft, diffused highlights and eliminate harsh shadows. The camera angle is a slightly elevated 45-degree shot to showcase its clean lines. Ultra-realistic, with sharp focus on the steam rising from the coffee. Square image.",
)

for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text":
                print(content_block.text)
            elif content_block.type == "image":
                with open("product_mockup.png", "wb") as f:
                    f.write(base64.b64decode(content_block.data))

JavaScript

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

async function main() {
  const ai = new GoogleGenAI({});

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: "A high-resolution, studio-lit product photograph of a minimalist ceramic coffee mug in matte black, presented on a polished concrete surface. The lighting is a three-point softbox setup designed to create soft, diffused highlights and eliminate harsh shadows. The camera angle is a slightly elevated 45-degree shot to showcase its clean lines. Ultra-realistic, with sharp focus on the steam rising from the coffee. Square image.",
  });
  for (const step of interaction.steps) {
    if (step.type === "model_output") {
      for (const contentBlock of step.content) {
        if (contentBlock.type === "text") {
          console.log(contentBlock.text);
        } else if (contentBlock.type === "image") {
          const buffer = Buffer.from(contentBlock.data, "base64");
          fs.writeFileSync("product_mockup.png", buffer);
        }
      }
    }
  }
}

main();

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.ImageContent;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ModelOutputStep;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

Client client = new Client();

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(
            InteractionsInput.of(
                "A high-resolution, studio-lit product photograph of a minimalist ceramic coffee mug in matte black, presented on a polished concrete surface. The lighting is a three-point softbox setup designed to create soft, diffused highlights and eliminate harsh shadows. The camera angle is a slightly elevated 45-degree shot to showcase its clean lines. Ultra-realistic, with sharp focus on the steam rising from the coffee. Square image."))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

if (interaction.steps().isPresent()) {
  for (Step step : interaction.steps().get()) {
    if (step instanceof ModelOutputStep) {
      ModelOutputStep outputStep = (ModelOutputStep) step;
      if (outputStep.content().isPresent()) {
        for (Content contentBlock : outputStep.content().get()) {
          if (contentBlock instanceof TextContent) {
            System.out.println(((TextContent) contentBlock).text().orElse(""));
          } else if (contentBlock instanceof ImageContent) {
            ImageContent img = (ImageContent) contentBlock;
            if (img.data().isPresent()) {
              byte[] imgBytes = Base64.getDecoder().decode(img.data().get());
              Files.write(Paths.get("product_mockup.png"), imgBytes);
            }
          }
        }
      }
    }
  }
}

Go

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

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

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-nano-banana-2.1"),
            Input: interactions.NewInteractionsInput("A high-resolution, studio-lit product photograph of a minimalist ceramic coffee mug in matte black, presented on a polished concrete surface. The lighting is a three-point softbox setup designed to create soft, diffused highlights and eliminate harsh shadows. The camera angle is a slightly elevated 45-degree shot to showcase its clean lines. Ultra-realistic, with sharp focus on the steam rising from the coffee. Square image."),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    for _, step := range res.Interaction.Steps {
        if step.ModelOutputStep != nil {
            for _, contentBlock := range step.ModelOutputStep.Content {
                if contentBlock.TextContent != nil {
                    fmt.Println(contentBlock.TextContent.Text)
                } else if contentBlock.ImageContent != nil && contentBlock.ImageContent.Data != nil {
                    imgBytes, err := base64.StdEncoding.DecodeString(*contentBlock.ImageContent.Data)
                    if err != nil {
                        log.Fatal(err)
                    }
                    if err := os.WriteFile("product_mockup.png", imgBytes, 0644); err != nil {
                        log.Fatal(err)
                    }
                }
            }
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-nano-banana-2.1",
    "input": "A high-resolution, studio-lit product photograph of a minimalist ceramic coffee mug in matte black, presented on a polished concrete surface. The lighting is a three-point softbox setup designed to create soft, diffused highlights and eliminate harsh shadows. The camera angle is a slightly elevated 45-degree shot to showcase its clean lines. Ultra-realistic, with sharp focus on the steam rising from the coffee. Square image."
  }'
一张高分辨率、棚拍光效的极简风陶瓷咖啡杯商品照片…
一张高分辨率、影棚灯光效果的商品照片,画面中是一个简约陶瓷咖啡杯…

5. 极简和负空间设计

非常适合为网站、演示文稿或营销材料创建背景,以便在上面叠加文字。

模板

A minimalist composition featuring a single [subject] positioned in the
[bottom-right/top-left/etc.] of the frame. The background is a vast, empty
[color] canvas, creating significant negative space. Soft, subtle lighting.
[Aspect ratio].

提示

A minimalist composition featuring a single, delicate red maple leaf
positioned in the bottom-right of the frame. The background is a vast, empty
off-white canvas, creating significant negative space for text. Soft,
diffused lighting from the top left. Square image.

Python

from google import genai
import base64

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input="A minimalist composition featuring a single, delicate red maple leaf positioned in the bottom-right of the frame. The background is a vast, empty off-white canvas, creating significant negative space for text. Soft, diffused lighting from the top left. Square image.",
)

for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text":
                print(content_block.text)
            elif content_block.type == "image":
                with open("minimalist_design.png", "wb") as f:
                    f.write(base64.b64decode(content_block.data))

JavaScript

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

async function main() {
  const ai = new GoogleGenAI({});

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: "A minimalist composition featuring a single, delicate red maple leaf positioned in the bottom-right of the frame. The background is a vast, empty off-white canvas, creating significant negative space for text. Soft, diffused lighting from the top left. Square image.",
  });
  for (const step of interaction.steps) {
    if (step.type === "model_output") {
      for (const contentBlock of step.content) {
        if (contentBlock.type === "text") {
          console.log(contentBlock.text);
        } else if (contentBlock.type === "image") {
          const buffer = Buffer.from(contentBlock.data, "base64");
          fs.writeFileSync("minimalist_design.png", buffer);
        }
      }
    }
  }
}

main();

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.ImageContent;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ModelOutputStep;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

Client client = new Client();

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(
            InteractionsInput.of(
                "A minimalist composition featuring a single, delicate red maple leaf positioned in the bottom-right of the frame. The background is a vast, empty off-white canvas, creating significant negative space for text. Soft, diffused lighting from the top left. Square image."))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

if (interaction.steps().isPresent()) {
  for (Step step : interaction.steps().get()) {
    if (step instanceof ModelOutputStep) {
      ModelOutputStep outputStep = (ModelOutputStep) step;
      if (outputStep.content().isPresent()) {
        for (Content contentBlock : outputStep.content().get()) {
          if (contentBlock instanceof TextContent) {
            System.out.println(((TextContent) contentBlock).text().orElse(""));
          } else if (contentBlock instanceof ImageContent) {
            ImageContent img = (ImageContent) contentBlock;
            if (img.data().isPresent()) {
              byte[] imgBytes = Base64.getDecoder().decode(img.data().get());
              Files.write(Paths.get("minimalist_design.png"), imgBytes);
            }
          }
        }
      }
    }
  }
}

Go

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

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

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-nano-banana-2.1"),
            Input: interactions.NewInteractionsInput("A minimalist composition featuring a single, delicate red maple leaf positioned in the bottom-right of the frame. The background is a vast, empty off-white canvas, creating significant negative space for text. Soft, diffused lighting from the top left. Square image."),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    for _, step := range res.Interaction.Steps {
        if step.ModelOutputStep != nil {
            for _, contentBlock := range step.ModelOutputStep.Content {
                if contentBlock.TextContent != nil {
                    fmt.Println(contentBlock.TextContent.Text)
                } else if contentBlock.ImageContent != nil && contentBlock.ImageContent.Data != nil {
                    imgBytes, err := base64.StdEncoding.DecodeString(*contentBlock.ImageContent.Data)
                    if err != nil {
                        log.Fatal(err)
                    }
                    if err := os.WriteFile("minimalist_design.png", imgBytes, 0644); err != nil {
                        log.Fatal(err)
                    }
                }
            }
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-nano-banana-2.1",
    "input": "A minimalist composition featuring a single, delicate red maple leaf positioned in the bottom-right of the frame. The background is a vast, empty off-white canvas, creating significant negative space for text. Soft, diffused lighting from the top left. Square image."
  }'
极简风格的构图,画面中只有一片精致的红枫叶…
一幅极简主义构图,画面中只有一片精致的红枫叶…

6. 连环画(漫画分格 / 分镜脚本)

基于角色一致性和场景描述,创建用于视觉叙事的面板。为了确保文本准确性和叙事能力,这些提示最适合与 Gemini 3 Pro 和 Gemini 3.1 Flash Image 搭配使用。

模板

Make a 3 panel comic in a [style]. Put the character in a [type of scene].

提示

Make a 3 panel comic in a gritty, noir art style with high-contrast black and white inks. Put the character in a humurous scene.

Python

from google import genai
from PIL import Image
import base64

client = genai.Client()

with open('/path/to/your/man_in_white_glasses.jpg', 'rb') as f:
    image_bytes = f.read()
text_input = "Make a 3 panel comic in a gritty, noir art style with high-contrast black and white inks. Put the character in a humurous scene."

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input=[
        {"type": "text", "text": text_input},
        {
            "type": "image",
            "data": base64.b64encode(image_bytes).decode('utf-8'),
            "mime_type": "image/jpeg"
        }
    ],
)

for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text":
                print(content_block.text)
            elif content_block.type == "image":
                with open("comic_panel.jpg", "wb") as f:
                    f.write(base64.b64decode(content_block.data))

JavaScript

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

async function main() {
  const ai = new GoogleGenAI({});

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

  const input = [
    { type: "text", text: "Make a 3 panel comic in a gritty, noir art style with high-contrast black and white inks. Put the character in a humurous scene." },
    {
      type: "image",
      mime_type: "image/jpeg",
      data: base64Image
    },
  ];

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: input,
  });
  for (const step of interaction.steps) {
    if (step.type === "model_output") {
      for (const contentBlock of step.content) {
        if (contentBlock.type === "text") {
          console.log(contentBlock.text);
        } else if (contentBlock.type === "image") {
          const buffer = Buffer.from(contentBlock.data, "base64");
          fs.writeFileSync("comic_panel.jpg", buffer);
        }
      }
    }
  }
}

main();

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.ImageContent;
import com.google.genai.gaos.models.interactions.ImageContentMimeType;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ModelOutputStep;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;

Client client = new Client();

byte[] imageBytes = Files.readAllBytes(Paths.get("/path/to/your/man_in_white_glasses.jpg"));
String base64Image = Base64.getEncoder().encodeToString(imageBytes);
String textInput =
    "Make a 3 panel comic in a gritty, noir art style with high-contrast black and white inks. Put the character in a humurous scene.";

Content textContent = TextContent.builder().text(textInput).build();
Content imageContent =
    ImageContent.builder()
        .data(base64Image)
        .mimeType(ImageContentMimeType.IMAGE_JPEG)
        .build();

List<Content> contents = Arrays.asList(textContent, imageContent);

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(InteractionsInput.ofContent(contents))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

if (interaction.steps().isPresent()) {
  for (Step step : interaction.steps().get()) {
    if (step instanceof ModelOutputStep) {
      ModelOutputStep outputStep = (ModelOutputStep) step;
      if (outputStep.content().isPresent()) {
        for (Content contentBlock : outputStep.content().get()) {
          if (contentBlock instanceof TextContent) {
            System.out.println(((TextContent) contentBlock).text().orElse(""));
          } else if (contentBlock instanceof ImageContent) {
            ImageContent img = (ImageContent) contentBlock;
            if (img.data().isPresent()) {
              byte[] outBytes = Base64.getDecoder().decode(img.data().get());
              Files.write(Paths.get("comic_panel.jpg"), outBytes);
            }
          }
        }
      }
    }
  }
}

Go

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

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

    imageBytes, err := os.ReadFile("/path/to/your/man_in_white_glasses.jpg")
    if err != nil {
        log.Fatal(err)
    }
    base64Image := base64.StdEncoding.EncodeToString(imageBytes)
    textInput := "Make a 3 panel comic in a gritty, noir art style with high-contrast black and white inks. Put the character in a humurous scene."

    contents := []interactions.Content{
        interactions.NewContent(interactions.TextContent{
            Text: textInput,
        }),
        interactions.NewContent(interactions.ImageContent{
            Data:     genai.Ptr(base64Image),
            MimeType: interactions.ImageContentMimeTypeImageJpeg.ToPointer(),
        }),
    }

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-nano-banana-2.1"),
            Input: interactions.NewInteractionsInput(contents),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    for _, step := range res.Interaction.Steps {
        if step.ModelOutputStep != nil {
            for _, contentBlock := range step.ModelOutputStep.Content {
                if contentBlock.TextContent != nil {
                    fmt.Println(contentBlock.TextContent.Text)
                } else if contentBlock.ImageContent != nil && contentBlock.ImageContent.Data != nil {
                    outBytes, err := base64.StdEncoding.DecodeString(*contentBlock.ImageContent.Data)
                    if err != nil {
                        log.Fatal(err)
                    }
                    if err := os.WriteFile("comic_panel.jpg", outBytes, 0644); err != nil {
                        log.Fatal(err)
                    }
                }
            }
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-nano-banana-2.1",
    "input": [
      {"type": "text", "text": "Make a 3 panel comic in a gritty, noir art style with high-contrast black and white inks. Put the character in a humurous scene."},
      {"type": "image", "data": "<BASE64_IMAGE_DATA>", "mime_type": "image/jpeg"}
    ]
  }'

输入

输出

一位戴着白色眼镜的男士
输入图片
制作一个 3 格漫画,采用粗犷、黑色电影的艺术风格…
以冷酷、黑色电影的艺术风格制作一个 3 格漫画…

使用 Google 搜索,根据最新或实时信息生成图片。 这对于新闻、天气和其他时效性主题非常有用。

提示

Make a simple but stylish graphic of last night's Arsenal game in the Champion's League

Python

from google import genai
from google.genai import types
import base64

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input="Make a simple but stylish graphic of last night's Arsenal game in the Champion's League",
    tools=[{"type": "google_search"}],
    response_format={"type": "image", "aspect_ratio": "16:9"},
)

for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text":
                print(content_block.text)
            elif content_block.type == "image":
                with open("football-score.jpg", "wb") as f:
                    f.write(base64.b64decode(content_block.data))

JavaScript

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

async function main() {
  const ai = new GoogleGenAI({});

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: "Make a simple but stylish graphic of last night's Arsenal game in the Champion's League",
    tools: [{ type: "google_search" }],
    response_format: { type: "image", aspect_ratio: "16:9", image_size: "2K" },
  });

  for (const step of interaction.steps) {
    if (step.type === "model_output") {
      for (const contentBlock of step.content) {
        if (contentBlock.type === "text") {
          console.log(contentBlock.text);
        } else if (contentBlock.type === "image") {
          const buffer = Buffer.from(contentBlock.data, "base64");
          fs.writeFileSync("football-score.jpg", buffer);
        }
      }
    }
  }
}

main();

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.CreateModelInteractionResponseFormat;
import com.google.genai.gaos.models.interactions.GoogleSearch;
import com.google.genai.gaos.models.interactions.ImageContent;
import com.google.genai.gaos.models.interactions.ImageResponseFormat;
import com.google.genai.gaos.models.interactions.ImageResponseFormatAspectRatio;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ModelOutputStep;
import com.google.genai.gaos.models.interactions.ResponseFormat;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;

Client client = new Client();

CreateModelInteractionResponseFormat format =
    CreateModelInteractionResponseFormat.of(
        ResponseFormat.of(
            ImageResponseFormat.builder()
                .aspectRatio(ImageResponseFormatAspectRatio.of("16:9"))
                .build()));

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(
            InteractionsInput.of(
                "Make a simple but stylish graphic of last night's Arsenal game in the Champion's League"))
        .tools(Arrays.asList(new GoogleSearch()))
        .responseFormat(format)
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

if (interaction.steps().isPresent()) {
  for (Step step : interaction.steps().get()) {
    if (step instanceof ModelOutputStep) {
      ModelOutputStep outputStep = (ModelOutputStep) step;
      if (outputStep.content().isPresent()) {
        for (Content contentBlock : outputStep.content().get()) {
          if (contentBlock instanceof TextContent) {
            System.out.println(((TextContent) contentBlock).text().orElse(""));
          } else if (contentBlock instanceof ImageContent) {
            ImageContent img = (ImageContent) contentBlock;
            if (img.data().isPresent()) {
              byte[] imgBytes = Base64.getDecoder().decode(img.data().get());
              Files.write(Paths.get("football-score.jpg"), imgBytes);
            }
          }
        }
      }
    }
  }
}

Go

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

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

    format := interactions.NewCreateModelInteractionResponseFormat(
        interactions.NewResponseFormat(interactions.ImageResponseFormat{
            AspectRatio: interactions.ImageResponseFormatAspectRatio("16:9").ToPointer(),
        }),
    )

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-nano-banana-2.1"),
            Input: interactions.NewInteractionsInput("Make a simple but stylish graphic of last night's Arsenal game in the Champion's League"),
            Tools: []interactions.Tool{
                interactions.NewTool(interactions.GoogleSearch{}),
            },
            ResponseFormat: genai.Ptr(format),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    for _, step := range res.Interaction.Steps {
        if step.ModelOutputStep != nil {
            for _, contentBlock := range step.ModelOutputStep.Content {
                if contentBlock.TextContent != nil {
                    fmt.Println(contentBlock.TextContent.Text)
                } else if contentBlock.ImageContent != nil && contentBlock.ImageContent.Data != nil {
                    imgBytes, err := base64.StdEncoding.DecodeString(*contentBlock.ImageContent.Data)
                    if err != nil {
                        log.Fatal(err)
                    }
                    if err := os.WriteFile("football-score.jpg", imgBytes, 0644); err != nil {
                        log.Fatal(err)
                    }
                }
            }
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-nano-banana-2.1",
    "input": "Make a simple but stylish graphic of last nights Arsenal game in the Champions League",
    "tools": [{"type": "google_search"}],
    "response_format": {
      "type": "image",
      "aspect_ratio": "16:9"
    }
  }'
AI 生成的阿森纳足球队比分图
AI 生成的阿森纳足球队比分图

用于编辑图片的提示

这些示例展示了如何在提供文本提示词的同时提供图片,以便进行编辑、合成和风格迁移。

1. 添加和移除元素

提供图片并描述您想做的更改。模型会与原始图片的风格、光线和透视效果保持一致。

模板

Using the provided image of [subject], please [add/remove/modify] [element]
to/from the scene. Ensure the change is [description of how the change should
integrate].

提示

"Using the provided image of my cat, please add a small, knitted wizard hat
on its head. Make it look like it's sitting comfortably and matches the soft
lighting of the photo."

Python

from google import genai
from PIL import Image
import base64

client = genai.Client()

with open('/path/to/your/cat_photo.png', 'rb') as f:
    image_bytes = f.read()
text_input = """Using the provided image of my cat, please add a small, knitted wizard hat on its head. Make it look like it's sitting comfortably and not falling off."""

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input=[
        {"type": "text", "text": text_input},
        {
            "type": "image",
            "data": base64.b64encode(image_bytes).decode('utf-8'),
            "mime_type": "image/png"
        }
    ],
)

for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text":
                print(content_block.text)
            elif content_block.type == "image":
                with open("cat_with_hat.png", "wb") as f:
                    f.write(base64.b64decode(content_block.data))

JavaScript

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

async function main() {
  const ai = new GoogleGenAI({});

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

  const input = [
    { type: "text", text: "Using the provided image of my cat, please add a small, knitted wizard hat on its head. Make it look like it's sitting comfortably and not falling off." },
    {
      type: "image",
      mime_type: "image/png",
      data: base64Image
    },
  ];

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: input,
  });
  for (const step of interaction.steps) {
    if (step.type === "model_output") {
      for (const contentBlock of step.content) {
        if (contentBlock.type === "text") {
          console.log(contentBlock.text);
        } else if (contentBlock.type === "image") {
          const buffer = Buffer.from(contentBlock.data, "base64");
          fs.writeFileSync("cat_with_hat.png", buffer);
        }
      }
    }
  }
}

main();

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.ImageContent;
import com.google.genai.gaos.models.interactions.ImageContentMimeType;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ModelOutputStep;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;

Client client = new Client();

byte[] imageBytes = Files.readAllBytes(Paths.get("/path/to/your/cat_photo.png"));
String base64Image = Base64.getEncoder().encodeToString(imageBytes);
String textInput =
    "Using the provided image of my cat, please add a small, knitted wizard hat on its head. Make it look like it's sitting comfortably and not falling off.";

Content textContent = TextContent.builder().text(textInput).build();
Content imageContent =
    ImageContent.builder()
        .data(base64Image)
        .mimeType(ImageContentMimeType.IMAGE_PNG)
        .build();

List<Content> contents = Arrays.asList(textContent, imageContent);

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(InteractionsInput.ofContent(contents))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

if (interaction.steps().isPresent()) {
  for (Step step : interaction.steps().get()) {
    if (step instanceof ModelOutputStep) {
      ModelOutputStep outputStep = (ModelOutputStep) step;
      if (outputStep.content().isPresent()) {
        for (Content contentBlock : outputStep.content().get()) {
          if (contentBlock instanceof TextContent) {
            System.out.println(((TextContent) contentBlock).text().orElse(""));
          } else if (contentBlock instanceof ImageContent) {
            ImageContent img = (ImageContent) contentBlock;
            if (img.data().isPresent()) {
              byte[] outBytes = Base64.getDecoder().decode(img.data().get());
              Files.write(Paths.get("cat_with_hat.png"), outBytes);
            }
          }
        }
      }
    }
  }
}

Go

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

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

    imageBytes, err := os.ReadFile("/path/to/your/cat_photo.png")
    if err != nil {
        log.Fatal(err)
    }
    base64Image := base64.StdEncoding.EncodeToString(imageBytes)
    textInput := "Using the provided image of my cat, please add a small, knitted wizard hat on its head. Make it look like it's sitting comfortably and not falling off."

    contents := []interactions.Content{
        interactions.NewContent(interactions.TextContent{
            Text: textInput,
        }),
        interactions.NewContent(interactions.ImageContent{
            Data:     genai.Ptr(base64Image),
            MimeType: interactions.ImageContentMimeTypeImagePng.ToPointer(),
        }),
    }

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-nano-banana-2.1"),
            Input: interactions.NewInteractionsInput(contents),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    for _, step := range res.Interaction.Steps {
        if step.ModelOutputStep != nil {
            for _, contentBlock := range step.ModelOutputStep.Content {
                if contentBlock.TextContent != nil {
                    fmt.Println(contentBlock.TextContent.Text)
                } else if contentBlock.ImageContent != nil && contentBlock.ImageContent.Data != nil {
                    outBytes, err := base64.StdEncoding.DecodeString(*contentBlock.ImageContent.Data)
                    if err != nil {
                        log.Fatal(err)
                    }
                    if err := os.WriteFile("cat_with_hat.png", outBytes, 0644); err != nil {
                        log.Fatal(err)
                    }
                }
            }
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
    -H "x-goog-api-key: $GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -d "{
      \"model\": \"gemini-nano-banana-2.1\",
      \"input\": [
            {\"type\": \"text\", \"text\": \"Using the provided image of my cat, please add a small, knitted wizard hat on its head. Make it look like it's sitting comfortably and not falling off.\"},
            {\"type\": \"image\", \"mime_type\":\"image/png\", \"data\": \"<BASE64_IMAGE_DATA>\"}
        ]
    }"

输入

输出

一张照片般逼真的图片,画面中有一只毛茸茸的姜黄色猫咪。
一只毛茸茸的姜黄色猫的逼真图片…
根据我提供的猫咪图片,请添加一顶小巧的针织巫师帽…
请使用我提供的猫咪图片,为它添加一顶小小的针织巫师帽…

2. 局部重绘(语义遮罩)

通过对话方式定义“蒙版”,修改图片的特定部分,同时保持其余部分不变。

模板

Using the provided image, change only the [specific element] to [new
element/description]. Keep everything else in the image exactly the same,
preserving the original style, lighting, and composition.

提示

"Using the provided image of a living room, change only the blue sofa to be
a vintage, brown leather chesterfield sofa. Keep the rest of the room,
including the pillows on the sofa and the lighting, unchanged."

Python

from google import genai
from PIL import Image
import base64

client = genai.Client()

with open('/path/to/your/living_room.png', 'rb') as f:
    image_bytes = f.read()
text_input = """Using the provided image of a living room, change only the blue sofa to be a vintage, brown leather chesterfield sofa. Keep the rest of the room, including the pillows on the sofa and the lighting, unchanged."""

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input=[
        {
            "type": "image",
            "data": base64.b64encode(image_bytes).decode('utf-8'),
            "mime_type": "image/png"
        },
        {"type": "text", "text": text_input}
    ],
)

for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text":
                print(content_block.text)
            elif content_block.type == "image":
                with open("living_room_edited.png", "wb") as f:
                    f.write(base64.b64decode(content_block.data))

JavaScript

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

async function main() {
  const ai = new GoogleGenAI({});

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

  const input = [
    {
      type: "image",
      mime_type: "image/png",
      data: base64Image
    },
    { type: "text", text: "Using the provided image of a living room, change only the blue sofa to be a vintage, brown leather chesterfield sofa. Keep the rest of the room, including the pillows on the sofa and the lighting, unchanged." },
  ];

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: input,
  });
  for (const step of interaction.steps) {
    if (step.type === "model_output") {
      for (const contentBlock of step.content) {
        if (contentBlock.type === "text") {
          console.log(contentBlock.text);
        } else if (contentBlock.type === "image") {
          const buffer = Buffer.from(contentBlock.data, "base64");
          fs.writeFileSync("living_room_edited.png", buffer);
        }
      }
    }
  }
}

main();

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.ImageContent;
import com.google.genai.gaos.models.interactions.ImageContentMimeType;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ModelOutputStep;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;

Client client = new Client();

byte[] imageBytes = Files.readAllBytes(Paths.get("/path/to/your/living_room.png"));
String base64Image = Base64.getEncoder().encodeToString(imageBytes);
String textInput =
    "Using the provided image of a living room, change only the blue sofa to be a vintage, brown leather chesterfield sofa. Keep the rest of the room, including the pillows on the sofa and the lighting, unchanged.";

Content imageContent =
    ImageContent.builder()
        .data(base64Image)
        .mimeType(ImageContentMimeType.IMAGE_PNG)
        .build();
Content textContent = TextContent.builder().text(textInput).build();

List<Content> contents = Arrays.asList(imageContent, textContent);

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(InteractionsInput.ofContent(contents))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

if (interaction.steps().isPresent()) {
  for (Step step : interaction.steps().get()) {
    if (step instanceof ModelOutputStep) {
      ModelOutputStep outputStep = (ModelOutputStep) step;
      if (outputStep.content().isPresent()) {
        for (Content contentBlock : outputStep.content().get()) {
          if (contentBlock instanceof TextContent) {
            System.out.println(((TextContent) contentBlock).text().orElse(""));
          } else if (contentBlock instanceof ImageContent) {
            ImageContent img = (ImageContent) contentBlock;
            if (img.data().isPresent()) {
              byte[] outBytes = Base64.getDecoder().decode(img.data().get());
              Files.write(Paths.get("living_room_edited.png"), outBytes);
            }
          }
        }
      }
    }
  }
}

Go

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

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

    imageBytes, err := os.ReadFile("/path/to/your/living_room.png")
    if err != nil {
        log.Fatal(err)
    }
    base64Image := base64.StdEncoding.EncodeToString(imageBytes)
    textInput := "Using the provided image of a living room, change only the blue sofa to be a vintage, brown leather chesterfield sofa. Keep the rest of the room, including the pillows on the sofa and the lighting, unchanged."

    contents := []interactions.Content{
        interactions.NewContent(interactions.ImageContent{
            Data:     genai.Ptr(base64Image),
            MimeType: interactions.ImageContentMimeTypeImagePng.ToPointer(),
        }),
        interactions.NewContent(interactions.TextContent{
            Text: textInput,
        }),
    }

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-nano-banana-2.1"),
            Input: interactions.NewInteractionsInput(contents),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    for _, step := range res.Interaction.Steps {
        if step.ModelOutputStep != nil {
            for _, contentBlock := range step.ModelOutputStep.Content {
                if contentBlock.TextContent != nil {
                    fmt.Println(contentBlock.TextContent.Text)
                } else if contentBlock.ImageContent != nil && contentBlock.ImageContent.Data != nil {
                    outBytes, err := base64.StdEncoding.DecodeString(*contentBlock.ImageContent.Data)
                    if err != nil {
                        log.Fatal(err)
                    }
                    if err := os.WriteFile("living_room_edited.png", outBytes, 0644); err != nil {
                        log.Fatal(err)
                    }
                }
            }
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
    -H "x-goog-api-key: $GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -d "{
      \"model\": \"gemini-nano-banana-2.1\",
      \"input\": [
        {\"type\": \"image\", \"mime_type\":\"image/png\", \"data\": \"<BASE64_IMAGE_DATA>\"},
        {\"type\": \"text\", \"text\": \"Using the provided image of a living room, change only the blue sofa to be a vintage, brown leather chesterfield sofa. Keep the rest of the room, including the pillows on the sofa and the lighting, unchanged.\"}
      ]
    }"

输入

输出

一个广角镜头,拍摄一个现代、光线充足的客厅…
一个现代、光线充足的客厅的广角镜头…
使用提供的客厅图片,仅将蓝色沙发改为复古棕色皮革切斯特菲尔德沙发…
使用提供的客厅图片,仅将蓝色沙发改为复古棕色皮革切斯特菲尔德沙发…

3. 风格迁移

提供一张图片,并要求模型以不同的艺术风格重新创建其内容。

模板

Transform the provided photograph of [subject] into the artistic style of [artist/art style]. Preserve the original composition but render it with [description of stylistic elements].

提示

"Transform the provided photograph of a modern city street at night into the artistic style of Vincent van Gogh's 'Starry Night'. Preserve the original composition of buildings and cars, but render all elements with swirling, impasto brushstrokes and a dramatic palette of deep blues and bright yellows."

Python

from google import genai
from PIL import Image
import base64

client = genai.Client()

with open('/path/to/your/city.png', 'rb') as f:
    image_bytes = f.read()
text_input = """Transform the provided photograph of a modern city street at night into the artistic style of Vincent van Gogh's 'Starry Night'. Preserve the original composition of buildings and cars, but render all elements with swirling, impasto brushstrokes and a dramatic palette of deep blues and bright yellows."""

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input=[
        {
            "type": "image",
            "data": base64.b64encode(image_bytes).decode('utf-8'),
            "mime_type": "image/png"
        },
        {"type": "text", "text": text_input}
    ],
)

for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text":
                print(content_block.text)
            elif content_block.type == "image":
                with open("city_style_transfer.png", "wb") as f:
                    f.write(base64.b64decode(content_block.data))

JavaScript

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

async function main() {
  const ai = new GoogleGenAI({});
  const imageData = fs.readFileSync("/path/to/your/city.png");
  const base64Image = imageData.toString("base64");

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: [
      {
        type: "image",
        mime_type: "image/png",
        data: base64Image
      },
      { type: "text", text: "Transform the provided photograph of a modern city street at night into the artistic style of Vincent van Gogh's 'Starry Night'. Preserve the original composition of buildings and cars, but render all elements with swirling, impasto brushstrokes and a dramatic palette of deep blues and bright yellows." },
    ],
  });
  for (const step of interaction.steps) {
    if (step.type === "model_output") {
      for (const contentBlock of step.content) {
        if (contentBlock.type === "text") {
          console.log(contentBlock.text);
        } else if (contentBlock.type === "image") {
          const buffer = Buffer.from(contentBlock.data, "base64");
          fs.writeFileSync("city_style_transfer.png", buffer);
        }
      }
    }
  }
}

main();

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.ImageContent;
import com.google.genai.gaos.models.interactions.ImageContentMimeType;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ModelOutputStep;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;

Client client = new Client();

byte[] imageBytes = Files.readAllBytes(Paths.get("/path/to/your/city.png"));
String base64Image = Base64.getEncoder().encodeToString(imageBytes);
String textInput =
    "Transform the provided photograph of a modern city street at night into the artistic style of Vincent van Gogh's 'Starry Night'. Preserve the original composition of buildings and cars, but render all elements with swirling, impasto brushstrokes and a dramatic palette of deep blues and bright yellows.";

Content imageContent =
    ImageContent.builder()
        .data(base64Image)
        .mimeType(ImageContentMimeType.IMAGE_PNG)
        .build();
Content textContent = TextContent.builder().text(textInput).build();

List<Content> contents = Arrays.asList(imageContent, textContent);

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(InteractionsInput.ofContent(contents))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

if (interaction.steps().isPresent()) {
  for (Step step : interaction.steps().get()) {
    if (step instanceof ModelOutputStep) {
      ModelOutputStep outputStep = (ModelOutputStep) step;
      if (outputStep.content().isPresent()) {
        for (Content contentBlock : outputStep.content().get()) {
          if (contentBlock instanceof TextContent) {
            System.out.println(((TextContent) contentBlock).text().orElse(""));
          } else if (contentBlock instanceof ImageContent) {
            ImageContent img = (ImageContent) contentBlock;
            if (img.data().isPresent()) {
              byte[] outBytes = Base64.getDecoder().decode(img.data().get());
              Files.write(Paths.get("city_style_transfer.png"), outBytes);
            }
          }
        }
      }
    }
  }
}

Go

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

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

    imageBytes, err := os.ReadFile("/path/to/your/city.png")
    if err != nil {
        log.Fatal(err)
    }
    base64Image := base64.StdEncoding.EncodeToString(imageBytes)
    textInput := "Transform the provided photograph of a modern city street at night into the artistic style of Vincent van Gogh's 'Starry Night'. Preserve the original composition of buildings and cars, but render all elements with swirling, impasto brushstrokes and a dramatic palette of deep blues and bright yellows."

    contents := []interactions.Content{
        interactions.NewContent(interactions.ImageContent{
            Data:     genai.Ptr(base64Image),
            MimeType: interactions.ImageContentMimeTypeImagePng.ToPointer(),
        }),
        interactions.NewContent(interactions.TextContent{
            Text: textInput,
        }),
    }

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-nano-banana-2.1"),
            Input: interactions.NewInteractionsInput(contents),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    for _, step := range res.Interaction.Steps {
        if step.ModelOutputStep != nil {
            for _, contentBlock := range step.ModelOutputStep.Content {
                if contentBlock.TextContent != nil {
                    fmt.Println(contentBlock.TextContent.Text)
                } else if contentBlock.ImageContent != nil && contentBlock.ImageContent.Data != nil {
                    outBytes, err := base64.StdEncoding.DecodeString(*contentBlock.ImageContent.Data)
                    if err != nil {
                        log.Fatal(err)
                    }
                    if err := os.WriteFile("city_style_transfer.png", outBytes, 0644); err != nil {
                        log.Fatal(err)
                    }
                }
            }
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
    -H "x-goog-api-key: $GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -d "{
      \"model\": \"gemini-nano-banana-2.1\",
      \"input\": [
        {\"type\": \"image\", \"mime_type\":\"image/png\", \"data\": \"<BASE64_IMAGE_DATA>\"},
        {\"type\": \"text\", \"text\": \"Transform the provided photograph of a modern city street at night into the artistic style of Vincent van Gogh's 'Starry Night'. Preserve the original composition of buildings and cars, but render all elements with swirling, impasto brushstrokes and a dramatic palette of deep blues and bright yellows.\"}
      ]
    }"

输入

输出

一张照片般逼真的高分辨率照片,画面中是繁忙的城市街道…
A photorealistic, high-resolution photograph of a busy city street…
将提供的现代城市街道夜景照片转换为…
转换提供的现代城市街道夜景照片…

4. 高级合成:组合多张图片

提供多张图片作为背景,打造全新合成场景。这非常适合产品视觉稿或创意拼图。

模板

Create a new image by combining the elements from the provided images. Take
the [element from image 1] and place it with/on the [element from image 2].
The final image should be a [description of the final scene].

提示

"Create a professional e-commerce fashion photo. Take the blue floral dress
from the first image and let the woman from the second image wear it.
Generate a realistic, full-body shot of the woman wearing the dress, with
the lighting and shadows adjusted to match the outdoor environment."

Python

from google import genai
from PIL import Image
import base64

client = genai.Client()

with open('/path/to/your/dress.png', 'rb') as f:
    dress_bytes = f.read()
with open('/path/to/your/model.png', 'rb') as f:
    model_bytes = f.read()
text_input = """Create a professional e-commerce fashion photo. Take the blue floral dress from the first image and let the woman from the second image wear it. Generate a realistic, full-body shot of the woman wearing the dress, with the lighting and shadows adjusted to match the outdoor environment."""

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input=[
        {
            "type": "image",
            "data": base64.b64encode(dress_bytes).decode('utf-8'),
            "mime_type": "image/png"
        },
        {
            "type": "image",
            "data": base64.b64encode(model_bytes).decode('utf-8'),
            "mime_type": "image/png"
        },
        {"type": "text", "text": text_input}
    ],
)

for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text":
                print(content_block.text)
            elif content_block.type == "image":
                with open("fashion_ecommerce_shot.png", "wb") as f:
                    f.write(base64.b64decode(content_block.data))

JavaScript

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

async function main() {
  const ai = new GoogleGenAI({});

  const imagePath1 = "/path/to/your/dress.png";
  const imageData1 = fs.readFileSync(imagePath1);
  const base64Image1 = imageData1.toString("base64");
  const imagePath2 = "/path/to/your/model.png";
  const imageData2 = fs.readFileSync(imagePath2);
  const base64Image2 = imageData2.toString("base64");

  const input = [
    {
      type: "image",
      mime_type: "image/png",
      data: base64Image1
    },
    {
      type: "image",
      mime_type: "image/png",
      data: base64Image2
    },
    { type: "text", text: "Create a professional e-commerce fashion photo. Take the blue floral dress from the first image and let the woman from the second image wear it. Generate a realistic, full-body shot of the woman wearing the dress, with the lighting and shadows adjusted to match the outdoor environment." },
  ];

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: input,
  });
  for (const step of interaction.steps) {
    if (step.type === "model_output") {
      for (const contentBlock of step.content) {
        if (contentBlock.type === "text") {
          console.log(contentBlock.text);
        } else if (contentBlock.type === "image") {
          const buffer = Buffer.from(contentBlock.data, "base64");
          fs.writeFileSync("fashion_ecommerce_shot.png", buffer);
        }
      }
    }
  }
}

main();

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.ImageContent;
import com.google.genai.gaos.models.interactions.ImageContentMimeType;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ModelOutputStep;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;

Client client = new Client();

byte[] dressBytes = Files.readAllBytes(Paths.get("/path/to/your/dress.png"));
byte[] modelBytes = Files.readAllBytes(Paths.get("/path/to/your/model.png"));
String textInput =
    "Create a professional e-commerce fashion photo. Take the blue floral dress from the first image and let the woman from the second image wear it. Generate a realistic, full-body shot of the woman wearing the dress, with the lighting and shadows adjusted to match the outdoor environment.";

Content dressContent =
    ImageContent.builder()
        .data(Base64.getEncoder().encodeToString(dressBytes))
        .mimeType(ImageContentMimeType.IMAGE_PNG)
        .build();
Content modelContent =
    ImageContent.builder()
        .data(Base64.getEncoder().encodeToString(modelBytes))
        .mimeType(ImageContentMimeType.IMAGE_PNG)
        .build();
Content textContent = TextContent.builder().text(textInput).build();

List<Content> contents = Arrays.asList(dressContent, modelContent, textContent);

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(InteractionsInput.ofContent(contents))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

if (interaction.steps().isPresent()) {
  for (Step step : interaction.steps().get()) {
    if (step instanceof ModelOutputStep) {
      ModelOutputStep outputStep = (ModelOutputStep) step;
      if (outputStep.content().isPresent()) {
        for (Content contentBlock : outputStep.content().get()) {
          if (contentBlock instanceof TextContent) {
            System.out.println(((TextContent) contentBlock).text().orElse(""));
          } else if (contentBlock instanceof ImageContent) {
            ImageContent img = (ImageContent) contentBlock;
            if (img.data().isPresent()) {
              byte[] outBytes = Base64.getDecoder().decode(img.data().get());
              Files.write(Paths.get("fashion_ecommerce_shot.png"), outBytes);
            }
          }
        }
      }
    }
  }
}

Go

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

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

    dressBytes, err := os.ReadFile("/path/to/your/dress.png")
    if err != nil {
        log.Fatal(err)
    }
    modelBytes, err := os.ReadFile("/path/to/your/model.png")
    if err != nil {
        log.Fatal(err)
    }
    textInput := "Create a professional e-commerce fashion photo. Take the blue floral dress from the first image and let the woman from the second image wear it. Generate a realistic, full-body shot of the woman wearing the dress, with the lighting and shadows adjusted to match the outdoor environment."

    contents := []interactions.Content{
        interactions.NewContent(interactions.ImageContent{
            Data:     genai.Ptr(base64.StdEncoding.EncodeToString(dressBytes)),
            MimeType: interactions.ImageContentMimeTypeImagePng.ToPointer(),
        }),
        interactions.NewContent(interactions.ImageContent{
            Data:     genai.Ptr(base64.StdEncoding.EncodeToString(modelBytes)),
            MimeType: interactions.ImageContentMimeTypeImagePng.ToPointer(),
        }),
        interactions.NewContent(interactions.TextContent{
            Text: textInput,
        }),
    }

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-nano-banana-2.1"),
            Input: interactions.NewInteractionsInput(contents),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    for _, step := range res.Interaction.Steps {
        if step.ModelOutputStep != nil {
            for _, contentBlock := range step.ModelOutputStep.Content {
                if contentBlock.TextContent != nil {
                    fmt.Println(contentBlock.TextContent.Text)
                } else if contentBlock.ImageContent != nil && contentBlock.ImageContent.Data != nil {
                    outBytes, err := base64.StdEncoding.DecodeString(*contentBlock.ImageContent.Data)
                    if err != nil {
                        log.Fatal(err)
                    }
                    if err := os.WriteFile("fashion_ecommerce_shot.png", outBytes, 0644); err != nil {
                        log.Fatal(err)
                    }
                }
            }
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
    -H "x-goog-api-key: $GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -d "{
      \"model\": \"gemini-nano-banana-2.1\",
      \"input\": [
            {\"type\": \"image\", \"mime_type\":\"image/png\", \"data\": \"<BASE64_IMAGE_DATA_1>\"},
            {\"type\": \"image\", \"mime_type\":\"image/png\", \"data\": \"<BASE64_IMAGE_DATA_2>\"},
            {\"type\": \"text\", \"text\": \"Create a professional e-commerce fashion photo. Take the blue floral dress from the first image and let the woman from the second image wear it. Generate a realistic, full-body shot of the woman wearing the dress, with the lighting and shadows adjusted to match the outdoor environment.\"}
      }]
    }"

输入值 1

输入值 2

输出

中性背景下的蓝色碎花夏季连衣裙
中性色背景上的蓝色花卉夏季连衣裙
一位梳着发髻的女性的全身照…
Full-body shot of a woman with her hair in a bun…
一位身穿蓝色碎花夏装的女士在户外
一位身穿蓝色花卉夏季连衣裙的女士在户外场景中

5. 高保真细节保留

为确保在编辑过程中保留关键细节(例如面部或徽标),请在编辑请求中详细描述这些细节。

模板

Using the provided images, place [element from image 2] onto [element from
image 1]. Ensure that the features of [element from image 1] remain
completely unchanged. The added element should [description of how the
element should integrate].

提示

"Take the first image of the woman with brown hair, blue eyes, and a neutral
expression. Add the logo from the second image onto her black t-shirt.
Ensure the woman's face and features remain completely unchanged. The logo
should look like it's naturally printed on the fabric, following the folds
of the shirt."

Python

from google import genai
from PIL import Image
import base64

client = genai.Client()

with open('/path/to/your/woman.png', 'rb') as f:
    woman_bytes = f.read()
with open('/path/to/your/logo.png', 'rb') as f:
    logo_bytes = f.read()
text_input = """Take the first image of the woman with brown hair, blue eyes, and a neutral expression. Add the logo from the second image onto her black t-shirt. Ensure the woman's face and features remain completely unchanged. The logo should look like it's naturally printed on the fabric, following the folds of the shirt."""

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input=[
      {"type": "image", "mime_type":"image/png", "data": base64.b64encode(woman_bytes).decode('utf-8')},
      {"type": "image", "mime_type":"image/png", "data": base64.b64encode(logo_bytes).decode('utf-8')},
      {"type": "text", "text": text_input}
    ],
)

for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text":
                print(content_block.text)
            elif content_block.type == "image":
                with open("woman_with_logo.png", "wb") as f:
                    f.write(base64.b64decode(content_block.data))

JavaScript

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

async function main() {
  const ai = new GoogleGenAI({});

  const imagePath1 = "/path/to/your/woman.png";
  const imageData1 = fs.readFileSync(imagePath1);
  const base64Image1 = imageData1.toString("base64");
  const imagePath2 = "/path/to/your/logo.png";
  const imageData2 = fs.readFileSync(imagePath2);
  const base64Image2 = imageData2.toString("base64");

  const input = [
    {"type": "image", "mime_type":"image/png", "data": base64Image1},
    {"type": "image", "mime_type":"image/png", "data": base64Image2},
    {"type": "text", "text": "Take the first image of the woman with brown hair, blue eyes, and a neutral expression. Add the logo from the second image onto her black t-shirt. Ensure the woman's face and features remain completely unchanged. The logo should look like it's naturally printed on the fabric, following the folds of the shirt."},
  ];

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: input,
  });
  for (const step of interaction.steps) {
    if (step.type === "model_output") {
      for (const contentBlock of step.content) {
        if (contentBlock.type === "text") {
          console.log(contentBlock.text);
        } else if (contentBlock.type === "image") {
          const buffer = Buffer.from(contentBlock.data, "base64");
          fs.writeFileSync("woman_with_logo.png", buffer);
        }
      }
    }
  }
}

main();

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.ImageContent;
import com.google.genai.gaos.models.interactions.ImageContentMimeType;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ModelOutputStep;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;

Client client = new Client();

byte[] womanBytes = Files.readAllBytes(Paths.get("/path/to/your/woman.png"));
byte[] logoBytes = Files.readAllBytes(Paths.get("/path/to/your/logo.png"));
String textInput =
    "Take the first image of the woman with brown hair, blue eyes, and a neutral expression. Add the logo from the second image onto her black t-shirt. Ensure the woman's face and features remain completely unchanged. The logo should look like it's naturally printed on the fabric, following the folds of the shirt.";

Content womanContent =
    ImageContent.builder()
        .data(Base64.getEncoder().encodeToString(womanBytes))
        .mimeType(ImageContentMimeType.IMAGE_PNG)
        .build();
Content logoContent =
    ImageContent.builder()
        .data(Base64.getEncoder().encodeToString(logoBytes))
        .mimeType(ImageContentMimeType.IMAGE_PNG)
        .build();
Content textContent = TextContent.builder().text(textInput).build();

List<Content> contents = Arrays.asList(womanContent, logoContent, textContent);

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(InteractionsInput.ofContent(contents))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

if (interaction.steps().isPresent()) {
  for (Step step : interaction.steps().get()) {
    if (step instanceof ModelOutputStep) {
      ModelOutputStep outputStep = (ModelOutputStep) step;
      if (outputStep.content().isPresent()) {
        for (Content contentBlock : outputStep.content().get()) {
          if (contentBlock instanceof TextContent) {
            System.out.println(((TextContent) contentBlock).text().orElse(""));
          } else if (contentBlock instanceof ImageContent) {
            ImageContent img = (ImageContent) contentBlock;
            if (img.data().isPresent()) {
              byte[] outBytes = Base64.getDecoder().decode(img.data().get());
              Files.write(Paths.get("woman_with_logo.png"), outBytes);
            }
          }
        }
      }
    }
  }
}

Go

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

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

    womanBytes, err := os.ReadFile("/path/to/your/woman.png")
    if err != nil {
        log.Fatal(err)
    }
    logoBytes, err := os.ReadFile("/path/to/your/logo.png")
    if err != nil {
        log.Fatal(err)
    }
    textInput := "Take the first image of the woman with brown hair, blue eyes, and a neutral expression. Add the logo from the second image onto her black t-shirt. Ensure the woman's face and features remain completely unchanged. The logo should look like it's naturally printed on the fabric, following the folds of the shirt."

    contents := []interactions.Content{
        interactions.NewContent(interactions.ImageContent{
            Data:     genai.Ptr(base64.StdEncoding.EncodeToString(womanBytes)),
            MimeType: interactions.ImageContentMimeTypeImagePng.ToPointer(),
        }),
        interactions.NewContent(interactions.ImageContent{
            Data:     genai.Ptr(base64.StdEncoding.EncodeToString(logoBytes)),
            MimeType: interactions.ImageContentMimeTypeImagePng.ToPointer(),
        }),
        interactions.NewContent(interactions.TextContent{
            Text: textInput,
        }),
    }

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-nano-banana-2.1"),
            Input: interactions.NewInteractionsInput(contents),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    for _, step := range res.Interaction.Steps {
        if step.ModelOutputStep != nil {
            for _, contentBlock := range step.ModelOutputStep.Content {
                if contentBlock.TextContent != nil {
                    fmt.Println(contentBlock.TextContent.Text)
                } else if contentBlock.ImageContent != nil && contentBlock.ImageContent.Data != nil {
                    outBytes, err := base64.StdEncoding.DecodeString(*contentBlock.ImageContent.Data)
                    if err != nil {
                        log.Fatal(err)
                    }
                    if err := os.WriteFile("woman_with_logo.png", outBytes, 0644); err != nil {
                        log.Fatal(err)
                    }
                }
            }
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
    -H "x-goog-api-key: $GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -d "{
      \"model\": \"gemini-nano-banana-2.1\",
      \"input\": [
        {\"type\": \"image\", \"mime_type\":\"image/png\", \"data\": \"<BASE64_IMAGE_DATA_1>\"},
        {\"type\": \"image\", \"mime_type\":\"image/png\", \"data\": \"<BASE64_IMAGE_DATA_2>\"},
        {\"type\": \"text\", \"text\": \"Take the first image of the woman with brown hair, blue eyes, and a neutral expression. Add the logo from the second image onto her black t-shirt. Ensure the woman's face and features remain completely unchanged. The logo should look like it's naturally printed on the fabric, following the folds of the shirt.\"}
      ]
    }"

输入值 1

输入值 2

输出

一位留着棕色头发、长着蓝色眼睛的女性的专业头像…
一位棕发蓝眼女性的专业头像照…
由字母 G 和 A 组成的现代品牌标识
带有字母 G 和 A 的现代品牌标识
以第一张图片为例,图片中是一位留着棕色头发、有着蓝色眼睛、面无表情的女性…
以第一张图片为例,图片中是一位留着棕色头发、有着蓝色眼睛、表情自然的女性…

6. 让创意落地成真

上传草图或绘图,并让模型将其优化为成品图片。

模板

Turn this rough [medium] sketch of a [subject] into a [style description]
photo. Keep the [specific features] from the sketch but add [new details/materials].

提示

"Turn this rough pencil sketch of a futuristic car into a polished photo of the finished concept car in a showroom. Keep the sleek lines and low profile from the sketch but add metallic blue paint and neon rim lighting."

Python

from google import genai
from PIL import Image
import base64

client = genai.Client()

with open('/path/to/your/car_sketch.png', 'rb') as f:
    sketch_bytes = f.read()
text_input = """Turn this rough pencil sketch of a futuristic car into a polished photo of the finished concept car in a showroom. Keep the sleek lines and low profile from the sketch but add metallic blue paint and neon rim lighting."""

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input=[
      {"type": "image", "mime_type":"image/png", "data": base64.b64encode(sketch_bytes).decode('utf-8')},
      {"type": "text", "text": text_input}
    ],
)

for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text":
                print(content_block.text)
            elif content_block.type == "image":
                with open("car_photo.png", "wb") as f:
                    f.write(base64.b64decode(content_block.data))

JavaScript

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

async function main() {
  const ai = new GoogleGenAI({});

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

  const input = [
    {"type": "image", "mime_type":"image/png", "data": base64Image},
    {"type": "text", "text": "Turn this rough pencil sketch of a futuristic car into a polished photo of the finished concept car in a showroom. Keep the sleek lines and low profile from the sketch but add metallic blue paint and neon rim lighting."},
  ];

  const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: input,
  });
  for (const step of interaction.steps) {
    if (step.type === "model_output") {
      for (const contentBlock of step.content) {
        if (contentBlock.type === "text") {
          console.log(contentBlock.text);
        } else if (contentBlock.type === "image") {
          const buffer = Buffer.from(contentBlock.data, "base64");
          fs.writeFileSync("car_photo.png", buffer);
        }
      }
    }
  }
}

main();

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.ImageContent;
import com.google.genai.gaos.models.interactions.ImageContentMimeType;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ModelOutputStep;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;

Client client = new Client();

byte[] sketchBytes = Files.readAllBytes(Paths.get("/path/to/your/car_sketch.png"));
String textInput =
    "Turn this rough pencil sketch of a futuristic car into a polished photo of the finished concept car in a showroom. Keep the sleek lines and low profile from the sketch but add metallic blue paint and neon rim lighting.";

Content sketchContent =
    ImageContent.builder()
        .data(Base64.getEncoder().encodeToString(sketchBytes))
        .mimeType(ImageContentMimeType.IMAGE_PNG)
        .build();
Content textContent = TextContent.builder().text(textInput).build();

List<Content> contents = Arrays.asList(sketchContent, textContent);

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(InteractionsInput.ofContent(contents))
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

if (interaction.steps().isPresent()) {
  for (Step step : interaction.steps().get()) {
    if (step instanceof ModelOutputStep) {
      ModelOutputStep outputStep = (ModelOutputStep) step;
      if (outputStep.content().isPresent()) {
        for (Content contentBlock : outputStep.content().get()) {
          if (contentBlock instanceof TextContent) {
            System.out.println(((TextContent) contentBlock).text().orElse(""));
          } else if (contentBlock instanceof ImageContent) {
            ImageContent img = (ImageContent) contentBlock;
            if (img.data().isPresent()) {
              byte[] outBytes = Base64.getDecoder().decode(img.data().get());
              Files.write(Paths.get("car_photo.png"), outBytes);
            }
          }
        }
      }
    }
  }
}

Go

package main

import (
    "context"
    "encoding/base64"
    "fmt"
    "log"
    "os"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

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

    sketchBytes, err := os.ReadFile("/path/to/your/car_sketch.png")
    if err != nil {
        log.Fatal(err)
    }
    textInput := "Turn this rough pencil sketch of a futuristic car into a polished photo of the finished concept car in a showroom. Keep the sleek lines and low profile from the sketch but add metallic blue paint and neon rim lighting."

    contents := []interactions.Content{
        interactions.NewContent(interactions.ImageContent{
            Data:     genai.Ptr(base64.StdEncoding.EncodeToString(sketchBytes)),
            MimeType: interactions.ImageContentMimeTypeImagePng.ToPointer(),
        }),
        interactions.NewContent(interactions.TextContent{
            Text: textInput,
        }),
    }

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model: interactions.Model("gemini-nano-banana-2.1"),
            Input: interactions.NewInteractionsInput(contents),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }

    for _, step := range res.Interaction.Steps {
        if step.ModelOutputStep != nil {
            for _, contentBlock := range step.ModelOutputStep.Content {
                if contentBlock.TextContent != nil {
                    fmt.Println(contentBlock.TextContent.Text)
                } else if contentBlock.ImageContent != nil && contentBlock.ImageContent.Data != nil {
                    outBytes, err := base64.StdEncoding.DecodeString(*contentBlock.ImageContent.Data)
                    if err != nil {
                        log.Fatal(err)
                    }
                    if err := os.WriteFile("car_photo.png", outBytes, 0644); err != nil {
                        log.Fatal(err)
                    }
                }
            }
        }
    }
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
    -H "x-goog-api-key: $GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -d "{
      \"model\": \"gemini-nano-banana-2.1\",
      \"input\": [
        {\"type\": \"image\", \"mime_type\":\"image/png\", \"data\": \"<BASE64_IMAGE_DATA>\"},
        {\"type\": \"text\", \"text\": \"Turn this rough pencil sketch of a futuristic car into a polished photo of the finished concept car in a showroom. Keep the sleek lines and low profile from the sketch but add metallic blue paint and neon rim lighting.\"}
      ]
    }"

输入

输出

汽车草图
汽车草图
显示最终概念车的输出
汽车的精修照片

7. 角色一致性:360 度全景视图

您可以通过反复提示不同角度来生成角色的 360 度视图。为获得最佳效果,请在后续提示中添加之前生成的图片,以保持一致性。对于复杂姿势,请添加所选姿势的参考图片。

模板

A studio portrait of [person] against [background], [looking forward/in profile looking right/etc.]

提示

A studio portrait of this man against white, in profile looking right

Python

from google import genai
from PIL import Image
import base64

client = genai.Client()

with open('/path/to/your/man_in_white_glasses.jpg', 'rb') as f:
    image_bytes = f.read()
text_input = """A studio portrait of this man against white, in profile looking right"""

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input={
      {"type": "text", "text": text_input},
      {"type": "image", "mime_type":"image/png", "data": base64.b64encode(image_bytes).decode('utf-8')}
    },
)

for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text":
                print(content_block.text)
            elif content_block.type == "image":
                with open("man_right_profile.png", "wb") as f:
                    f.write(base64.b64decode(content_block.data))

输入

输出内容 1

输出内容 2

原始输入:一位戴着白色眼镜的男士
原始图片
输出图片:一位戴着白色眼镜的男子看向右侧
戴着白色眼镜的男子看向右侧
输出图片:一位戴着白色眼镜的男士向前看
一位戴着白色眼镜的男士向前看

最佳做法

为了让您的结果从优秀提升到卓越,请将这些专业策略融入您的工作流程中。

  • 内容要非常具体:提供的信息越详细,您对输出结果的控制力就越强。与其使用“奇幻盔甲”,不如具体描述:“华丽的精灵板甲,蚀刻着银叶图案,带有高领和猎鹰翅膀形状的肩甲”。
  • 提供上下文和意图:说明图片的用途。模型对上下文的理解会影响最终输出。例如,“为高端极简护肤品牌设计徽标”的效果要好于“设计徽标”。
  • 迭代和优化:不要指望第一次尝试就能生成完美的图片。利用模型的对话特性进行细微调整。接着输入提示,例如“很好,但能让光线更暖一些吗?”或“保持其他内容不变,但让角色的表情更严肃一些”。
  • 使用分步说明:对于包含许多元素的复杂场景,请将提示拆分为多个步骤。“首先,创建一个宁静、薄雾弥漫的黎明森林的背景。然后,在前景中添加一个长满苔藓的古老石制祭坛。 最后,将一把发光的剑放在祭坛顶部。”
  • 使用“语义否定提示”:不要说“没有汽车”,而是通过说“一条没有交通迹象的空旷、荒凉的街道”来正面描述场景。
  • 控制镜头:使用摄影和电影语言来控制构图。wide-angle shot、macro shot、low-angle perspective等字词。

限制

  • 为获得最佳性能,请使用以下语言:英语、阿拉伯语(埃及)、德语(德国)、西班牙语(墨西哥)、法语(法国)、印地语(印度)、印度尼西亚语(印度尼西亚)、意大利语(意大利)、日语(日本)、韩语(韩国)、葡萄牙语(巴西)、俄语(俄罗斯)、乌克兰语(乌克兰)、越南语(越南)、中文(中国)。
  • 图片生成不支持音频输入。只有 Gemini Nano Banana 2.1、Gemini 3.1 Flash Image 和 Gemini 3.1 Flash Lite Image 支持视频输入。
  • 模型不一定会严格按照用户明确要求的数量输出图片。
  • gemini-2.5-flash-image 最多支持 3 张图片作为输入,而 gemini-3-pro-image 支持 5 张高保真图片,总共最多支持 14 张图片。gemini-nano-banana-2.1 和 gemini-3.1-flash-image 在单个工作流中支持多达 4 个角色的相似度和多达 10 个物体的保真度。
  • 在为图片生成文本时,如果先生成文本,再要求生成包含该文本的图片,Gemini 的效果会最佳。
  • gemini-nano-banana-2.1 和 gemini-3.1-flash-image 依托 Google 搜索进行接地目前不支持使用网页搜索中的真实人物图片。
  • 生成的所有图片都包含 SynthID 水印。

可选配置

您可以选择使用 response_format 参数来配置输出格式、宽高比和图片大小。

输出格式

模型默认返回文本和图片回答。您可以通过在 response_format 参数中指定图片格式,将回答配置为仅返回生成的图片(省略对话文本)。

如需请求多种模态(例如文本和生成的图片),请改为向 response_format 传递一个格式条目数组。

Python

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input="Write a short poem about a starry night and generate an image of it.",
    response_format=[
        {"type": "text"},
        {"type": "image"},
    ],
)

JavaScript

const interaction = await ai.interactions.create({
  model: "gemini-nano-banana-2.1",
  input: "Write a short poem about a starry night and generate an image of it.",
  response_format: [
    { type: "text" },
    { type: "image" },
  ],
});

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.CreateModelInteractionResponseFormat;
import com.google.genai.gaos.models.interactions.ImageResponseFormat;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ResponseFormat;
import com.google.genai.gaos.models.interactions.TextResponseFormat;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.Arrays;

Client client = new Client();

CreateModelInteractionResponseFormat format =
    CreateModelInteractionResponseFormat.of(
        Arrays.asList(
            ResponseFormat.of(TextResponseFormat.builder().build()),
            ResponseFormat.of(ImageResponseFormat.builder().build())));

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(
            InteractionsInput.of(
                "Write a short poem about a starry night and generate an image of it."))
        .responseFormat(format)
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

Go

package main

import (
    "context"
    "log"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

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

    format := interactions.NewCreateModelInteractionResponseFormat([]interactions.ResponseFormat{
        interactions.NewResponseFormat(interactions.TextResponseFormat{}),
        interactions.NewResponseFormat(interactions.ImageResponseFormat{}),
    })

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model:          interactions.Model("gemini-nano-banana-2.1"),
            Input:          interactions.NewInteractionsInput("Write a short poem about a starry night and generate an image of it."),
            ResponseFormat: genai.Ptr(format),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }
    _ = res
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "gemini-nano-banana-2.1",
    "input": "Write a short poem about a starry night and generate an image of it.",
    "response_format": [
      { "type": "text" },
      { "type": "image" }
    ]
  }'

宽高比和图片尺寸

默认情况下,模型会使输出图片的大小与输入图片的大小一致,否则会生成 1:1 的方形图片。当 type 设置为 "image" 时,您可以使用 response_format 下的 aspect_ratio 和 image_size 字段来控制输出图片的宽高比和尺寸。

Python

interaction = client.interactions.create(
    model="gemini-nano-banana-2.1",
    input=prompt,
    response_format={
        "type": "image",
        "aspect_ratio": "16:9",
        "image_size": "2K",
    },
)

JavaScript

const interaction = await ai.interactions.create({
    model: "gemini-nano-banana-2.1",
    input: prompt,
    response_format: {
      type: "image",
      aspect_ratio: "16:9",
      image_size: "2K",
    },
  });

Java

import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.CreateModelInteractionResponseFormat;
import com.google.genai.gaos.models.interactions.ImageResponseFormat;
import com.google.genai.gaos.models.interactions.ImageResponseFormatAspectRatio;
import com.google.genai.gaos.models.interactions.ImageResponseFormatImageSize;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ResponseFormat;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;

Client client = new Client();
String prompt = "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme";

CreateModelInteractionResponseFormat format =
    CreateModelInteractionResponseFormat.of(
        ResponseFormat.of(
            ImageResponseFormat.builder()
                .aspectRatio(ImageResponseFormatAspectRatio.of("16:9"))
                .imageSize(ImageResponseFormatImageSize.TWO_K)
                .build()));

CreateModelInteraction params =
    CreateModelInteraction.builder()
        .model(Model.of("gemini-nano-banana-2.1"))
        .input(InteractionsInput.of(prompt))
        .responseFormat(format)
        .build();

Interaction interaction =
    client.interactions.create(CreateInteractionRequestBody.of(params)).interaction().get();

Go

package main

import (
    "context"
    "log"

    "google.golang.org/genai"
    "google.golang.org/genai/interactions/models/interactions"
    "google.golang.org/genai/interactions/models/operations"
)

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

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

    format := interactions.NewCreateModelInteractionResponseFormat(
        interactions.NewResponseFormat(interactions.ImageResponseFormat{
            AspectRatio: interactions.ImageResponseFormatAspectRatio("16:9").ToPointer(),
            ImageSize:   interactions.ImageResponseFormatImageSizeTwoK.ToPointer(),
        }),
    )

    res, err := client.Interactions.Create(ctx, operations.CreateInteractionRequest{
        Body: operations.NewCreateInteractionRequestBody(interactions.CreateModelInteraction{
            Model:          interactions.Model("gemini-nano-banana-2.1"),
            Input:          interactions.NewInteractionsInput(prompt),
            ResponseFormat: genai.Ptr(format),
        }),
    })
    if err != nil {
        log.Fatal(err)
    }
    _ = res
}

REST

curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "gemini-nano-banana-2.1",
    "input": "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme",
    "response_format": {
      "type": "image",
      "aspect_ratio": "16:9",
      "image_size": "2K"
    }
  }'

下表列出了可用的不同比例以及生成的图片大小:

Nano Banana 2.1

宽高比 1K 分辨率 1,000 个 token 2K 分辨率 2,000 个 token 4K 分辨率 4,000 个 token
1:1 1024x1024 1120 2048 x 2048 1680 4096x4096 2520
1:4 512x2048 1120 1024x4096 1680 2048x8192 2520
1:8 384x3072 1120 768x6144 1680 1536x12288 2520
2:3 848x1264 1120 1696x2528 1680 3392x5056 2520
3:2 1264x848 1120 2528x1696 1680 5056x3392 2520
3:4 896x1200 1120 1792x2400 1680 3584x4800 2520
4:1 2048x512 1120 4096x1024 1680 8192x2048 2520
4:3 1200x896 1120 2400x1792 1680 4800x3584 2520
4:5 928x1152 1120 1856x2304 1680 3712x4608 2520
5:4 1152x928 1120 2304x1856 1680 4608x3712 2520
8:1 3072x384 1120 6144x768 1680 12288x1536 2520
9:16 768x1376 1120 1536x2752 1680 3072x5504 2520
16:9 1376x768 1120 2752x1536 1680 5504x3072 2520
21:9 1584x672 1120 3168x1344 1680 6336x2688 2520

3.1 Flash Image

宽高比 512 像素分辨率 500 个 token 1K 分辨率 1,000 个 token 2K 分辨率 2,000 个 token 4K 分辨率 4,000 个 token
1:1 512x512 747 1024x1024 1120 2048 x 2048 1680 4096x4096 2520
1:4 256x1024 747 512x2048 1120 1024x4096 1680 2048x8192 2520
1:8 192x1536 747 384x3072 1120 768x6144 1680 1536x12288 2520
2:3 424x632 747 848x1264 1120 1696x2528 1680 3392x5056 2520
3:2 632x424 747 1264x848 1120 2528x1696 1680 5056x3392 2520
3:4 448x600 747 896x1200 1120 1792x2400 1680 3584x4800 2520
4:1 1024x256 747 2048x512 1120 4096x1024 1680 8192x2048 2520
4:3 600x448 747 1200x896 1120 2400x1792 1680 4800x3584 2520
4:5 464x576 747 928x1152 1120 1856x2304 1680 3712x4608 2520
5:4 576x464 747 1152x928 1120 2304x1856 1680 4608x3712 2520
8:1 1536x192 747 3072x384 1120 6144x768 1680 12288x1536 2520
9:16 384x688 747 768x1376 1120 1536x2752 1680 3072x5504 2520
16:9 688x384 747 1376x768 1120 2752x1536 1680 5504x3072 2520
21:9 792x168 747 1584x672 1120 3168x1344 1680 6336x2688 2520

3.1 Pro Image

宽高比 1K 分辨率 1,000 个 token 2K 分辨率 2,000 个 token 4K 分辨率 4,000 个 token
1:1 1024x1024 1120 2048 x 2048 1120 4096x4096 2000
2:3 848x1264 1120 1696x2528 1120 3392x5056 2000
3:2 1264x848 1120 2528x1696 1120 5056x3392 2000
3:4 896x1200 1120 1792x2400 1120 3584x4800 2000
4:3 1200x896 1120 2400x1792 1120 4800x3584 2000
4:5 928x1152 1120 1856x2304 1120 3712x4608 2000
5:4 1152x928 1120 2304x1856 1120 4608x3712 2000
9:16 768x1376 1120 1536x2752 1120 3072x5504 2000
16:9 1376x768 1120 2752x1536 1120 5504x3072 2000
21:9 1584x672 1120 3168x1344 1120 6336x2688 2000

Gemini 2.5 Flash 图片

宽高比 分辨率 令牌
1:1 1024x1024 1290
2:3 832x1248 1290
3:2 1248x832 1290
3:4 864x1184 1290
4:3 1184x864 1290
4:5 896x1152 1290
5:4 1152x896 1290
9:16 768x1344 1290
16:9 1344x768 1290
21:9 1536x672 1290

何时使用 Imagen

Imagen 已停用,无法再通过 Gemini API 使用。 使用 Nano Banana 生成和编辑图片。

后续步骤

  • 查看 Veo 指南,了解如何使用 Gemini API 生成视频。
  • 如需详细了解 Gemini 模型,请参阅 Gemini 模型。