Nano Banana 圖像生成功能
- 您也可以使用提示詞自行建構:
-
由 Nano Banana 2 生成 提示:「一張光面雜誌封面的相片,簡約的藍色封面上有粗體大字『Nano Banana』。文字採用 Serif 字型,填滿整個畫面。不含其他文字。文字前方有一張肖像照,主角穿著簡約時尚的洋裝。她俏皮地拿著數字 2,這是視覺焦點。
在角落加上期數和「2026 年 2 月」日期,並附上條碼。雜誌放在設計師商店的架子上,背景是橘色石膏牆。」 -
由 Nano Banana Pro 生成 提示:「呈現一個清楚的 45 度俯視等角迷你 3D 卡通倫敦場景,包含最具代表性的地標和建築元素。使用柔和精緻的紋理、逼真的 PBR 材質,以及柔和寫實的光影。直接將當前天氣狀況融入城市環境,營造身歷其境的氛圍。採用簡潔、極簡的構圖,搭配柔和的純色背景。在頂端中央,以大型粗體文字顯示標題「倫敦」,下方是醒目的天氣圖示,接著是日期 (小型文字) 和溫度 (中型文字)。所有文字都必須置中,間距一致,且可稍微與建築物頂端重疊。」 -
由 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"}]
}'
接著,您可以使用 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"
}
}'
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\"
}
}"
以 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"
}
}'
回應包含 google_search_call 和 google_search_result 步驟,以及文字步驟的內嵌 url_citation 註解:
google_search_result:包含search_suggestions,這是一段 HTML 程式碼片段,用於在 UI 中顯示搜尋建議。url_citation註解:文字步驟中的內嵌引用,可將回覆內容連結至網頁來源。
以 Google 搜尋強化事實基礎,用於圖像 (Nano Banana 2.1 和 3.1 Flash)
使用 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 程式碼片段,用於在 UI 中顯示搜尋建議。
影片轉圖像生成 (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"
}
}'
生成解析度最高 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"
}
}'
以下是根據這則提示生成的圖片範例:
思考過程
Gemini 3 圖像模型是思考型模型,會使用推論程序 (「思考」) 處理複雜的提示。這項功能預設為啟用,無法在 API 中停用。如要進一步瞭解思考程序,請參閱 Gemini Thinking 指南。
模型最多會生成兩張過渡圖片,用於測試構圖和邏輯。「思考」中的最後一張圖片也是最終算繪的圖片。
你可以查看生成最終圖片的思考過程。
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"
}
}'
請注意,思考模型預設會對思考詞元計費,因為無論您是否查看思考過程,系統預設都會執行思考過程。
其他圖像生成模式
雖然 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."
}'
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"
}
}'
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"}
]
}'
輸入 |
輸出內容 |
|
|
7. 以 Google 搜尋建立基準
使用 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"
}
}'
編輯圖片的提示
以下範例說明如何提供圖片和文字提示詞,進行編輯、組合和風格移轉。
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.\"}
]
}"
輸入 |
輸出內容 |
|
|
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 |
輸出內容 |
|
|
|
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 |
輸出內容 |
|
|
|
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」。
限制
- 為獲得最佳效能,請使用下列語言:英文、ar-EG、de-DE、es-MX、fr-FR、hi-IN、id-ID、it-IT、ja-JP、ko-KR、pt-BR、ru-RU、ua-UA、vi-VN、zh-CN。
- 圖像生成功能不支援音訊輸入。只有 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 個詞元 | 2K 解析度 | 2,000 個詞元 | 4K 解析度 | 4,000 個詞元 |
|---|---|---|---|---|---|---|
| 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 個詞元 | 1K 解析度 | 1,000 個詞元 | 2K 解析度 | 2,000 個詞元 | 4K 解析度 | 4,000 個詞元 |
|---|---|---|---|---|---|---|---|---|
| 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 個詞元 | 2K 解析度 | 2,000 個詞元 | 4K 解析度 | 4,000 個詞元 |
|---|---|---|---|---|---|---|
| 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 Image
| 顯示比例 | 解析度 | 詞元 |
|---|---|---|
| 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 生成及編輯圖像。