Bildgenerierung mit Nano Banana
- Sie können auch eigene Prompts erstellen:
-
Von Nano Banana 2 generiert Prompt: „Ein Foto eines Hochglanzmagazin-Covers, das minimalistische blaue Cover hat die großen, fettgedruckten Wörter Nano Banana. Der Text ist in einer Serifenschriftart und füllt die Ansicht aus. Kein weiterer Text. Vor dem Text ist ein Porträt einer Person in einem eleganten und minimalistischen Kleid zu sehen. Sie hält spielerisch die Zahl 2, die den Schwerpunkt bildet.
Füge die Ausgabennummer und das Datum „Feb 2026“ in der Ecke zusammen mit einem Barcode hinzu. Das Magazin liegt in einem Designergeschäft auf einem Regal vor einer orangefarbenen verputzten Wand.“ -
Mit Nano Banana Pro generiert Prompt: „Erstelle eine klare, isometrische 3D-Miniatur-Cartoon-Szene von London aus der 45°-Draufsicht, die die bekanntesten Sehenswürdigkeiten und architektonischen Elemente der Stadt zeigt. Verwende weiche, feine Texturen mit realistischen PBR-Materialien und sanfter, lebensechter Beleuchtung und Schatten. Integrieren Sie die aktuellen Wetterbedingungen direkt in die Stadtumgebung, um eine immersive atmosphärische Stimmung zu erzeugen. Verwende eine klare, minimalistische Komposition mit einem weichen, einfarbigen Hintergrund. Platziere oben in der Mitte den Titel „London“ in großer Schrift im Fettdruck, darunter ein auffälliges Wettersymbol, dann das Datum (kleine Schrift) und die Temperatur (mittelgroße Schrift). Der gesamte Text muss zentriert sein und einen einheitlichen Abstand haben. Er darf die Oberseiten der Gebäude leicht überlappen.“ -
Von Nano Banana 2 generiert Prompt: „Finde über die Bildersuche Bilder, die einen Quetzal genau darstellen. Erstelle ein schönes Hintergrundbild im Format 3:2 von diesem Vogel mit einem natürlichen Farbverlauf von oben nach unten und einer minimalistischen Komposition.“ -
Mit Nano Banana Pro generiert Prompt: „Platziere dieses Logo auf einer hochwertigen Anzeige für ein Parfüm mit Bananenduft. Das Logo ist perfekt in die Flasche integriert.“ -
Mit Nano Banana Pro generiert Prompt: „Ein Foto einer Alltagsszene in einem gut besuchten Café, in dem Frühstück serviert wird. Im Vordergrund ist ein Anime-Mann mit blauen Haaren zu sehen, eine der Personen ist eine Bleistiftskizze, eine andere ist eine Claymation-Figur.“ -
Mit Nano Banana Pro generiert Prompt: „Finde über die Suche heraus, wie die Einführung von Gemini 3 Flash aufgenommen wurde. Verfasse anhand dieser Informationen einen kurzen Artikel mit Überschriften. Gib ein Foto des Artikels zurück, wie er in einem designorientierten Hochglanzmagazin erschienen ist. Es ist ein Foto einer einzelnen umgeklappten Seite, auf der der Artikel über Gemini 3 Flash zu sehen ist. Ein Hero-Foto. Headline in serif." -
Mit Nano Banana Pro generiert Prompt: „Ein Symbol, das einen niedlichen Hund darstellt. Der Hintergrund ist weiß. Erstelle die Symbole in einem farbenfrohen und haptischen 3D-Stil. Kein Text.“ -
Von Nano Banana 2 generiert Prompt: „Erstelle ein Foto, das perfekt isometrisch ist. Es ist keine Miniatur, sondern ein Foto, das zufällig perfekt isometrisch ist. Es ist ein Foto eines schönen modernen Gartens. Es gibt einen großen Pool in Form einer 2 und den Text „Nano Banana 2“.“
Nano Banana ist der Name für die nativen Funktionen zur Bildgenerierung von Gemini. Gemini kann Bilder dialogorientiert generieren und verarbeiten, und zwar mit Text, Bildern, Videos oder einer Kombination daraus. So können Sie visuelle Elemente mit beispielloser Kontrolle erstellen, bearbeiten und iterieren.
Modellauswahl
Nano Banana bezieht sich auf die folgenden Modelle, die in der Gemini API verfügbar sind:
- Nano Banana 2.1 (Gemini Nano Banana 2.1) (
gemini-nano-banana-2.1): Ein Update für Nano Banana 2, das als primäres, hocheffizientes Modell für die Bildgenerierung und die Bearbeitung im Dialog dient. Es bietet die Geschwindigkeit und Kosteneffizienz von Flash, liefert aber eine verbesserte visuelle Qualität, Textrendering, Konsistenz über mehrere Runden und Fundierung in der Google Suche bei Auflösungen von 1K, 2K und 4K. - Nano Banana 2 Lite (Gemini 3.1 Flash Lite Image) (
gemini-3.1-flash-lite-image): Das schnellste und günstigste Gemini-Bildmodell, das für Geschwindigkeit und Skalierbarkeit entwickelt wurde, wenn Geschwindigkeit und Kosten die primären operativen Einschränkungen sind. Nicht für mehrere Referenzeingaben oder sequenzielle Bearbeitung in mehreren Schritten optimiert. - Nano Banana 2 (Gemini 3.1 Flash Image)
(
gemini-3.1-flash-image): Das hocheffiziente Arbeitstier der vorherigen Generation, das Geschwindigkeit mit 4K-Generierung, Weltwissen und Konsistenz bei mehreren Referenzbildern verbindet. Für alle neuen Projekte wird die Verwendung von Nano Banana 2.1 empfohlen. - Nano Banana Pro (Gemini 3 Pro Image)
(
gemini-3-pro-image): Die Premium-Option für die komplexesten visuellen Aufgaben. Sie bietet das höchste Maß an Weltwissen, erweiterte Lokalisierung, genaue Markenkonsistenz und präzise kreative Kontrolle. - Nano Banana (Gemini 2.5 Flash Image) (
gemini-2.5-flash-image): Der ursprüngliche Pionier der Nano Banana-Serie. Es ist zwar ein zuverlässiges Modell, aber wir empfehlen, zu Nano Banana 2 Lite zu migrieren, um von einer besseren Qualität, schnelleren Generierungsgeschwindigkeiten und niedrigeren API-Preisen zu profitieren.
Alle generierten Bilder enthalten ein SynthID-Wasserzeichen.
Bildgenerierung (Text-zu-Bild)
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"}
]
}'
Sie können generierte Bilddaten mit dem Attribut interaction.output_image abrufen, das den zuletzt generierten Bildblock zurückgibt. Weitere Informationen zu Komforteigenschaften finden Sie in der Übersicht über Interaktionen.
Bildbearbeitung (Text-und-Bild-zu-Bild)
Zur Erinnerung: Sie müssen die erforderlichen Rechte an den Bildern haben, die Sie hochladen möchten. Erstellen Sie keine Inhalte, durch die die Rechte anderer verletzt werden, einschließlich Videos oder Bildern, durch die andere getäuscht, belästigt oder geschädigt werden. Ihre Verwendung dieses auf generativer KI basierenden Dienstes unterliegt unserer Richtlinie zur unzulässigen Nutzung.
Sie können ein Bild bereitstellen und Text-Prompts verwenden, um Elemente hinzuzufügen, zu entfernen oder zu ändern, den Stil zu ändern oder die Farbkorrektur anzupassen.
Im folgenden Beispiel wird das Hochladen von base64-codierten Bildern veranschaulicht.
Informationen zu mehreren Bildern, größeren Nutzlasten und unterstützten MIME-Typen finden Sie auf der Seite Bildverständnis.
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>\"
}
]
}"
Multi-Turn-Bildbearbeitung
Du kannst weiterhin Bilder im Dialog generieren und bearbeiten. Multi-Turn-Unterhaltungen sind die empfohlene Methode, um Bilder zu iterieren. Im folgenden Beispiel wird ein Prompt zum Generieren einer Infografik zur Fotosynthese gezeigt.
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"}]
}'
Anschließend können Sie mit dem previous_interaction_id die Sprache der Grafik in Spanisch ändern.
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"
}
}'
Funktionen von Nano Banana
Nano Banana-Modelle bieten hochmoderne Bildgenerierung und ‑bearbeitung. Gemini Nano Banana 2.1 und Gemini 3.1 Flash Image sind für Geschwindigkeit und Anwendungsfälle mit hohem Volumen optimiert, während Gemini 3 Pro Image für die professionelle Asset-Produktion optimiert ist. Sie wurden entwickelt, um die anspruchsvollsten Workflows durch logisches Schlussfolgern zu bewältigen, und eignen sich hervorragend für komplexe, mehrstufige Erstellungs- und Änderungsaufgaben.
- Hochauflösende Ausgabe: Integrierte Funktionen zur Generierung von 1K-, 2K- und 4K-Bildern.
- Gemini 3.1 Flash Image bietet die kleinere Auflösung von 512 Pixel (0,5K), die von Gemini Nano Banana 2.1 nicht unterstützt wird.
- Gemini 3.1 Flash Lite Image unterstützt nur die 1K-Auflösung.
- Erweitertes Text-Rendering: Kann lesbaren, stilisierten Text für Infografiken, Menüs, Diagramme und Marketing-Assets generieren.
- Fundierung mit der Google Suche: Das Modell kann die Google Suche als Tool verwenden, um Fakten zu überprüfen und Bilder basierend auf Echtzeitdaten zu generieren (z.B. aktuelle Wetterkarten, Börsencharts, aktuelle Ereignisse).
- Wird vom Gemini 3.1 Flash Lite Image-Modell nicht unterstützt.
- Gemini Nano Banana 2.1 und Gemini 3.1 Flash Image bieten neben der Websuche auch die Integration der Fundierung mit der Google Bildersuche.
- Thinking-Modus: Das Modell verwendet einen „Thinking“-Prozess, um komplexe Prompts zu durchdenken. Es generiert Zwischenbilder (im Backend sichtbar, aber nicht in Rechnung gestellt), um die Komposition zu verfeinern, bevor die endgültige Ausgabe in hoher Qualität erstellt wird.
- Bis zu 14 Referenzbilder: Sie können bis zu 14 Referenzbilder kombinieren, um das endgültige Bild zu erstellen.
- Neue Seitenverhältnisse: Gemini 3.1 Flash Lite Image bietet die Seitenverhältnisse
1:1,3:2,2:3,3:4,4:3,4:5,5:4,9:16,16:9und21:9.
Bis zu 14 Referenzbilder verwenden
Mit Nano Banana-Modellen können Sie bis zu 14 Referenzbilder kombinieren. Diese 14 Bilder können Folgendes enthalten:
| Gemini 3.1 Flash Lite Image | Gemini Nano Banana 2.1 und Gemini 3.1 Flash Image | Gemini 3 Pro Image |
|---|---|---|
| Bis zu 14 Bilder von Objekten mit hoher Wiedergabetreue, die in das endgültige Bild eingefügt werden sollen | Bis zu 10 Bilder von Objekten mit hoher Wiedergabetreue, die in das endgültige Bild eingefügt werden sollen | Bis zu 6 Bilder von Objekten mit hoher Wiedergabetreue, die in das endgültige Bild eingefügt werden sollen |
| – | Bis zu 4 Bilder von Charakteren, um die Charakterkonsistenz beizubehalten | Bis zu 5 Bilder von Charakteren, um die Charakterkonsistenz beizubehalten |
| – | – | Bis zu 3 Bilder, die als Stilreferenzen verwendet werden sollen |
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\"
}
}"
Fundierung mit der Google Suche
Mit dem Google-Suchtool können Sie Bilder auf Grundlage von Echtzeitinformationen wie Wettervorhersagen, Börsendiagrammen oder aktuellen Ereignissen generieren.
Wenn Sie die Fundierung mit der Google Suche für die Bildgenerierung verwenden, werden bildbasierte Suchergebnisse nicht an das Generierungsmodell übergeben und sind nicht in der Antwort enthalten (siehe Fundierung mit der Google Bildersuche).
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"
}
}'
Die Antwort enthält die Schritte google_search_call und google_search_result sowie Inline-url_citation-Anmerkungen zum Textschritt:
google_search_result: Enthältsearch_suggestions, ein HTML-Snippet zum Rendern von Suchvorschlägen in Ihrer UI.url_citation-Anmerkungen: Inline-Zitate im Textschritt, die Teile der Antwort mit ihren Webquellen verknüpfen.
Fundierung mit der Google Suche für Bilder (Nano Banana 2.1 und 3.1 Flash)
Die Fundierung mit der Google Bildersuche ermöglicht es Modellen, Webbilder, die über die Google Bildersuche abgerufen wurden, als visuellen Kontext für die Bildgenerierung zu verwenden. Die Bildersuche ist ein neuer Suchtyp im bestehenden Tool „Fundierung mit der Google Suche“, der neben der standardmäßigen Websuche funktioniert.
Wenn Sie die Bildersuche aktivieren möchten, konfigurieren Sie das Tool google_search in Ihrer API-Anfrage und geben Sie image_search im Array search_types an. Die Bildersuche kann unabhängig von der Websuche oder zusammen mit ihr verwendet werden.
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"]}]
}'
Displayanforderungen
Wenn Sie die Bildersuche im Rahmen der Fundierung mit der Google Suche verwenden, müssen Sie die search_suggestions aus dem Schritt google_search_result anzeigen. Die vollständigen Nutzungsanforderungen finden Sie in den Nutzungsbedingungen.
Antwort
Bei fundierten Antworten, die die Bildersuche verwenden, gibt die API Inline-Zitate und Attributionsmetadaten als Teil der Antwortschritte zurück:
url_citation-Anmerkungen: Inline-Zitate im Textinhaltsblock inmodel_output, die den generierten Inhalt mit seiner Quelle verknüpfen.google_search_result: Enthältsearch_suggestions, ein HTML-Snippet zum Rendern von Suchvorschlägen in Ihrer UI.
Video-zu-Bild-Generierung (Nano Banana 2.1, 3.1 Flash und 3.1 Flash Lite)
Mit der Video-zu-Bild-Generierung können Sie neue Bilder generieren, indem Sie den Kontext eines Videos als multimodale Referenz verwenden. Das ist nützlich, um hochwertige Video-Thumbnails, Filmplakate, zusammenfassende Infografiken oder neue Kunstwerke zu erstellen, die von einer Videoszene inspiriert sind.
Während der Generierung analysiert das Modell die Videoframes im Kontext, um visuelle Themen und Schlüsselereignisse zu extrahieren. Diese werden dann zusammen mit Ihrem Text-Prompt verwendet, um das Ausgabebild zu synthetisieren.
Sie können öffentliche YouTube-URLs direkt in Ihrer API-Anfrage übergeben oder lokale Videodateien mit der Files API hochladen.
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"
}
}'
Bilder mit einer Auflösung von bis zu 4K generieren
Gemini 3-Bildmodelle generieren standardmäßig 1K-Bilder, können aber auch 2K-, 4K- und 512-Pixel-Bilder (0,5K) ausgeben (nur Gemini 3.1 Flash Image). Wenn Sie Assets mit höherer Auflösung generieren möchten, geben Sie die image_size in der response_format an.
Sie müssen ein großes „K“ verwenden (z.B. 512 px (05.K), 1K, 2K, 4K). Parameter in Kleinbuchstaben (z.B. „1k“) werden abgelehnt.
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"
}
}'
Hier ist ein Beispielbild, das mit diesem Prompt generiert wurde:
Denkprozess
Gemini 3-Bildmodelle sind Thinking Models, die für komplexe Prompts einen Denkprozess („Thinking“) verwenden. Diese Funktion ist standardmäßig aktiviert und kann in der API nicht deaktiviert werden. Weitere Informationen zum Denkprozess finden Sie im Leitfaden zu Gemini Thinking.
Das Modell generiert bis zu zwei Zwischenbilder, um die Komposition und Logik zu testen. Das letzte Bild im Bereich „Thinking“ ist auch das endgültige gerenderte Bild.
Sie können sich die Gedanken ansehen, die zur Erstellung des endgültigen Bildes geführt haben.
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);
}
}
}
}
}
}
}
Ok
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)
}
}
}
}
}
}
Verschachtelte Texte und Bilder
Während Standardmodelle zur Bildgenerierung nur Bilder ausgeben, können einige erweiterte Gemini 3-Modelle (z. B. gemini-3-pro-image) verschachtelte Inhalte generieren, z. B. Geschichten oder Anleitungen, die sowohl Textblöcke als auch Illustrationen in derselben Antwort enthalten.
Da die Ausgabe komplex und verschachtelt ist, wird die vollständige Sequenz nicht von praktischen Attributen wie .output_image oder .output_text erfasst. Wenn Sie auf verschachtelte Inhalte zugreifen und diese speichern möchten, müssen Sie steps manuell iterieren:
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++;
}
}
}
}
}
}
}
Ok
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++
}
}
}
}
}
Denkaufwand steuern
Mit Gemini Nano Banana 2.1, Gemini 3.1 Flash Image und Gemini 3.1 Flash Lite Image können Sie den Umfang der Denkprozesse des Modells steuern, um Qualität und Latenz auszubalancieren:
| Modell | Unterstützte Denkaufwände | Standard |
|---|---|---|
| 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"
}
}'
Beachten Sie, dass Thinking-Tokens standardmäßig für Thinking-Modelle in Rechnung gestellt werden, da der Thinking-Prozess standardmäßig immer stattfindet, unabhängig davon, ob Sie den Prozess sehen oder nicht.
Andere Modi zur Bildgenerierung
Obwohl die Nano Banana-Modelle zur Bildgenerierung für die meisten Anwendungsfälle empfohlen werden, können Sie auch spezielle Modelle zur Bildgenerierung ausprobieren:
- Imagen: Die älteren Text-zu-Bild-Modelle von Google (eingestellt).
- Veo: Das Modell zur Videogenerierung von Google.
Bilder im Batch generieren
Alle auf dieser Seite beschriebenen Funktionen zur Bildgenerierung können auch als Batchjobs mit der Batch API ausgeführt werden. Das ist ideal, wenn Sie viele Bilder generieren müssen. Sie erhalten höhere Ratenbegrenzungen, die Bearbeitungszeit beträgt jedoch bis zu 24 Stunden.
Anleitung und Strategien für Prompts
In diesem Abschnitt finden Sie Beispiele für Prompts und Vorlagen für gängige Workflows zur Bildgenerierung und ‑bearbeitung. Jedes Beispiel enthält eine wiederverwendbare Vorlage und einen Beispiel-Prompt für die Interactions API.
Prompts zum Generieren von Bildern
Die folgenden Beispiele zeigen, wie Sie mit Text-Prompts verschiedene Arten von Bildern generieren können.
1. Fotorealistische Szenen
Eine Szene detailliert beschreiben Je genauer Sie sind, desto mehr Kontrolle haben Sie über die Ergebnisse.
Vorlage
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].
Prompt
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. Stilisierte Illustrationen und Sticker
Beschreiben Sie den künstlerischen Stil, das Motiv und das Medium. Geben Sie die visuellen Details (fette Linien, Farben usw.) genau an, um einheitliche Ergebnisse zu erhalten.
Vorlage
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].
Prompt
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. Korrekter Text in Bildern
Gemini ist hervorragend darin, Text zu rendern. Geben Sie den Text, die Schriftart (beschreibend) und das Gesamtdesign genau an. Mit Gemini 3 Pro Image professionelle Assets erstellen.
Vorlage
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].
Prompt
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. Produkt-Mockups und kommerzielle Fotografie
Perfekt für saubere, professionelle Produktaufnahmen für E-Commerce, Werbung oder Branding.
Vorlage
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].
Prompt
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. Minimalistisches Design und Negativraum
Hervorragend geeignet, um Hintergründe für Websites, Präsentationen oder Marketingmaterialien zu erstellen, auf denen Text eingeblendet wird.
Vorlage
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].
Prompt
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. Sequenzielle Kunst (Comic-Panel / Storyboard)
Baut auf der Charakterkonsistenz und der Szenenbeschreibung auf, um Panels für visuelles Storytelling zu erstellen. Für die Genauigkeit von Text und die Fähigkeit zum Storytelling funktionieren diese Prompts am besten mit Gemini 3 Pro und Gemini 3.1 Flash Image.
Vorlage
Make a 3 panel comic in a [style]. Put the character in a [type of scene].
Prompt
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"}
]
}'
Eingabe |
Ausgabe |
|
|
7. Fundierung mit der Google Suche
Mit der Google Suche können Sie Bilder auf Grundlage aktueller oder Echtzeitinformationen generieren. Das ist nützlich für Nachrichten, Wetter und andere zeitkritische Themen.
Prompt
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"
}
}'
Prompts zum Bearbeiten von Bildern
In diesen Beispielen wird gezeigt, wie Sie Bilder zusammen mit Ihren Text-Prompts für die Bearbeitung, Komposition und Stilübertragung bereitstellen.
1. Elemente hinzufügen und entfernen
Stellen Sie ein Bild bereit und beschreiben Sie die gewünschte Änderung. Das Modell entspricht dem Stil, der Beleuchtung und der Perspektive des Originalbilds.
Vorlage
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].
Prompt
"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>\"}
]
}"
Eingabe |
Ausgabe |
|
|
2. Inpainting (semantische Maskierung)
Sie können im Gespräch eine „Maske“ definieren, um einen bestimmten Teil eines Bildes zu bearbeiten, während der Rest unverändert bleibt.
Vorlage
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.
Prompt
"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.\"}
]
}"
Eingabe |
Ausgabe |
|
|
3. Stilübertragung
Stellen Sie ein Bild bereit und bitten Sie das Modell, den Inhalt in einem anderen künstlerischen Stil neu zu erstellen.
Vorlage
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].
Prompt
"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.\"}
]
}"
Eingabe |
Ausgabe |
|
|
4. Erweiterte Komposition: mehrere Bilder kombinieren
Stellen Sie mehrere Bilder als Kontext bereit, um eine neue, zusammengesetzte Szene zu erstellen. Das ist ideal für Produkt-Mockups oder kreative Collagen.
Vorlage
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].
Prompt
"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.\"}
}]
}"
Eingabe 1 |
Eingabe 2 |
Ausgabe |
|
|
|
5. High-Fidelity-Detailerhaltung
Damit wichtige Details (z. B. ein Gesicht oder Logo) bei einer Bearbeitung erhalten bleiben, beschreiben Sie sie zusammen mit Ihrer Bearbeitungsanfrage ausführlich.
Vorlage
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].
Prompt
"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.\"}
]
}"
Eingabe 1 |
Eingabe 2 |
Ausgabe |
|
|
|
6. Etwas zum Leben erwecken
Laden Sie eine grobe Skizze oder Zeichnung hoch und bitten Sie das Modell, sie zu einem fertigen Bild zu verfeinern.
Vorlage
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].
Prompt
"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.\"}
]
}"
Eingabe |
Ausgabe |
|
|
7. Gleichbleibende Darstellung von Charakteren: 360-Grad-Ansicht
Sie können 360-Grad-Ansichten einer Figur generieren, indem Sie iterativ Prompts für verschiedene Winkel eingeben. Die besten Ergebnisse erzielen Sie, wenn Sie zuvor generierte Bilder in nachfolgende Prompts einbeziehen, um die Konsistenz zu wahren. Fügen Sie bei komplexen Posen ein Referenzbild der ausgewählten Pose hinzu.
Vorlage
A studio portrait of [person] against [background], [looking forward/in profile looking right/etc.]
Prompt
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))
Eingabe |
Ausgabe 1 |
Ausgabe 2 |
|
|
|
Best Practices
Wenn Sie Ihre Ergebnisse von gut zu großartig verbessern möchten, sollten Sie diese professionellen Strategien in Ihren Workflow einbinden.
- Seien Sie so genau wie möglich:Je mehr Details Sie angeben, desto mehr Kontrolle haben Sie. Statt „Fantasy-Rüstung“ beschreiben Sie sie: „aufwendige Elfen-Rüstung mit eingravierten Silberblattmustern, mit einem hohen Kragen und Schulterstücken in Form von Falkenflügeln“.
- Kontext und Absicht angeben: Erklären Sie den Zweck des Bildes. Das Verständnis des Modells für den Kontext beeinflusst die endgültige Ausgabe. Beispiel: „Erstelle ein Logo für eine exklusive, minimalistische Hautpflegemarke“ liefert bessere Ergebnisse als nur „Erstelle ein Logo“.
- Wiederholen und verfeinern: Erwarten Sie nicht, dass Sie beim ersten Versuch ein perfektes Bild erhalten. Nutzen Sie die Konversationsfähigkeit des Modells, um kleine Änderungen vorzunehmen. Anschließend können Sie weitere Prompts eingeben, z. B. „Das ist toll, aber kannst du die Beleuchtung etwas wärmer machen?“ oder „Lass alles so, wie es ist, aber ändere den Gesichtsausdruck der Figur, sodass sie ernster wirkt.“
- Detaillierte Anleitung verwenden:Bei komplexen Szenen mit vielen Elementen sollten Sie Ihren Prompt in Schritte unterteilen. „Erstelle zuerst einen Hintergrund mit einem ruhigen, nebligen Wald im Morgengrauen. Füge dann im Vordergrund einen moosbedeckten, alten Steinaltar hinzu. Platziere dann ein einzelnes, leuchtendes Schwert auf dem Altar.“
- Semantische negative Prompts verwenden: Beschreiben Sie die gewünschte Szene positiv, anstatt „keine Autos“ zu sagen: „eine leere, verlassene Straße ohne Anzeichen von Verkehr“.
- Kamera steuern: Verwenden Sie fotografische und filmische Begriffe, um die Komposition zu steuern. Begriffe wie
wide-angle shot,macro shot,low-angle perspective.
Beschränkungen
- Die beste Leistung erzielen Sie mit den folgenden Sprachen: EN, 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.
- Die Bildgenerierung unterstützt keine Audioeingaben. Videoeingaben werden nur für Gemini Nano Banana 2.1, Gemini 3.1 Flash Image und Gemini 3.1 Flash Lite Image unterstützt.
- Das Modell gibt nicht immer genau die Anzahl von Bildern aus, die der Nutzer explizit anfordert.
gemini-2.5-flash-imagefunktioniert am besten mit bis zu 3 Bildern als Eingabe, währendgemini-3-pro-image5 Bilder mit hoher Qualität und insgesamt bis zu 14 Bilder unterstützt.gemini-nano-banana-2.1undgemini-3.1-flash-imageunterstützen die Ähnlichkeit von bis zu 4 Zeichen und die Genauigkeit von bis zu 10 Objekten in einem einzigen Workflow.- Wenn Sie Text für ein Bild generieren, funktioniert Gemini am besten, wenn Sie zuerst den Text generieren und dann nach einem Bild mit dem Text fragen.
gemini-nano-banana-2.1undgemini-3.1-flash-imageFundierung mit der Google Suche unterstützen derzeit nicht die Verwendung von realen Bildern von Personen aus der Websuche.- Alle generierten Bilder enthalten ein SynthID-Wasserzeichen.
Optionale Konfigurationen
Sie können das Ausgabeformat, das Seitenverhältnis und die Bildgröße optional mit dem Parameter response_format konfigurieren.
Ausgabeformat
Das Modell gibt standardmäßig sowohl Text- als auch Bildantworten zurück. Sie können die Antwort so konfigurieren, dass nur die KI-generierten Bilder zurückgegeben werden (ohne den Konversationstext). Geben Sie dazu im Parameter response_format ein Bildformat an.
Wenn Sie mehrere Modalitäten anfordern möchten (z. B. sowohl Text als auch das KI-generierte Bild), übergeben Sie stattdessen ein Array von Formateinträgen an 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" }
]
}'
Seitenverhältnisse und Bildgröße
Standardmäßig passt das Modell die Größe des Ausgabebildes an die des Eingabebildes an oder generiert quadratische Bilder im Format 1:1. Sie können das Seitenverhältnis und die Größe des Ausgabebilds mit den Feldern aspect_ratio und image_size unter response_format steuern, wenn type auf "image" festgelegt ist.
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"
}
}'
Die verschiedenen verfügbaren Seitenverhältnisse und die Größe des generierten Bildes sind in den folgenden Tabellen aufgeführt:
Nano Banana 2.1
| Seitenverhältnis | 1K-Auflösung | 1.000 Tokens | 2K-Auflösung | 2.000 Tokens | 4K-Auflösung | 4.000 Tokens |
|---|---|---|---|---|---|---|
| 1:1 | 1024x1024 | 1.120 | 2.048 x 2.048 | 1680 | 4096 x 4096 | 2520 |
| 1:4 | 512 × 2048 | 1.120 | 1024 × 4096 | 1680 | 2048 × 8192 | 2520 |
| 1:8 | 384 × 3072 | 1.120 | 768 × 6144 | 1680 | 1536x12288 | 2520 |
| 2:3 | 848 x 1264 | 1.120 | 1696 × 2528 | 1680 | 3392 × 5056 | 2520 |
| 3:2 | 1264 × 848 | 1.120 | 2528 × 1696 | 1680 | 5056 × 3392 | 2520 |
| 3:4 | 896 × 1200 | 1.120 | 1792 × 2400 | 1680 | 3584 × 4800 | 2520 |
| 4:1 | 2048 × 512 | 1.120 | 4096 x 1024 | 1680 | 8192 × 2048 | 2520 |
| 4:3 | 1200 × 896 | 1.120 | 2400 × 1792 | 1680 | 4800 × 3584 | 2520 |
| 4:5 | 928 × 1152 | 1.120 | 1856 × 2304 | 1680 | 3712 × 4608 | 2520 |
| 5:4 | 1152 x 928 | 1.120 | 2304 × 1856 | 1680 | 4608 × 3712 | 2520 |
| 8:1 | 3072 x 384 | 1.120 | 6144 × 768 | 1680 | 12288x1536 | 2520 |
| 9:16 | 768 × 1376 | 1.120 | 1536 × 2752 | 1680 | 3072 × 5504 | 2520 |
| 16:9 | 1376 × 768 | 1.120 | 2752 × 1536 | 1680 | 5504 × 3072 | 2520 |
| 21:9 | 1584 × 672 | 1.120 | 3168 × 1344 | 1680 | 6336 × 2688 | 2520 |
3.1 Flash Image
| Seitenverhältnis | Auflösung: 512 Pixel | 500 Tokens | 1K-Auflösung | 1.000 Tokens | 2K-Auflösung | 2.000 Tokens | 4K-Auflösung | 4.000 Tokens |
|---|---|---|---|---|---|---|---|---|
| 1:1 | 512 x 512 | 747 | 1024x1024 | 1.120 | 2.048 x 2.048 | 1680 | 4096 x 4096 | 2520 |
| 1:4 | 256 × 1024 | 747 | 512 × 2048 | 1.120 | 1024 × 4096 | 1680 | 2048 × 8192 | 2520 |
| 1:8 | 192 x 1536 | 747 | 384 × 3072 | 1.120 | 768 × 6144 | 1680 | 1536x12288 | 2520 |
| 2:3 | 424 × 632 | 747 | 848 x 1264 | 1.120 | 1696 × 2528 | 1680 | 3392 × 5056 | 2520 |
| 3:2 | 632 × 424 | 747 | 1264 × 848 | 1.120 | 2528 × 1696 | 1680 | 5056 × 3392 | 2520 |
| 3:4 | 448 × 600 | 747 | 896 × 1200 | 1.120 | 1792 × 2400 | 1680 | 3584 × 4800 | 2520 |
| 4:1 | 1024 × 256 | 747 | 2048 × 512 | 1.120 | 4096 x 1024 | 1680 | 8192 × 2048 | 2520 |
| 4:3 | 600 × 448 | 747 | 1200 × 896 | 1.120 | 2400 × 1792 | 1680 | 4800 × 3584 | 2520 |
| 4:5 | 464 x 576 | 747 | 928 × 1152 | 1.120 | 1856 × 2304 | 1680 | 3712 × 4608 | 2520 |
| 5:4 | 576 x 464 | 747 | 1152 x 928 | 1.120 | 2304 × 1856 | 1680 | 4608 × 3712 | 2520 |
| 8:1 | 1536 × 192 | 747 | 3072 x 384 | 1.120 | 6144 × 768 | 1680 | 12288x1536 | 2520 |
| 9:16 | 384 x 688 | 747 | 768 × 1376 | 1.120 | 1536 × 2752 | 1680 | 3072 × 5504 | 2520 |
| 16:9 | 688 × 384 | 747 | 1376 × 768 | 1.120 | 2752 × 1536 | 1680 | 5504 × 3072 | 2520 |
| 21:9 | 792 x 168 | 747 | 1584 × 672 | 1.120 | 3168 × 1344 | 1680 | 6336 × 2688 | 2520 |
3.1 Pro Image
| Seitenverhältnis | 1K-Auflösung | 1.000 Tokens | 2K-Auflösung | 2.000 Tokens | 4K-Auflösung | 4.000 Tokens |
|---|---|---|---|---|---|---|
| 1:1 | 1024x1024 | 1.120 | 2.048 x 2.048 | 1.120 | 4096 x 4096 | 2000 |
| 2:3 | 848 x 1264 | 1.120 | 1696 × 2528 | 1.120 | 3392 × 5056 | 2000 |
| 3:2 | 1264 × 848 | 1.120 | 2528 × 1696 | 1.120 | 5056 × 3392 | 2000 |
| 3:4 | 896 × 1200 | 1.120 | 1792 × 2400 | 1.120 | 3584 × 4800 | 2000 |
| 4:3 | 1200 × 896 | 1.120 | 2400 × 1792 | 1.120 | 4800 × 3584 | 2000 |
| 4:5 | 928 × 1152 | 1.120 | 1856 × 2304 | 1.120 | 3712 × 4608 | 2000 |
| 5:4 | 1152 x 928 | 1.120 | 2304 × 1856 | 1.120 | 4608 × 3712 | 2000 |
| 9:16 | 768 × 1376 | 1.120 | 1536 × 2752 | 1.120 | 3072 × 5504 | 2000 |
| 16:9 | 1376 × 768 | 1.120 | 2752 × 1536 | 1.120 | 5504 × 3072 | 2000 |
| 21:9 | 1584 × 672 | 1.120 | 3168 × 1344 | 1.120 | 6336 × 2688 | 2000 |
Gemini 2.5 Flash Image
| Seitenverhältnis | Auflösung | Tokens |
|---|---|---|
| 1:1 | 1024x1024 | 1290 |
| 2:3 | 832 × 1248 | 1290 |
| 3:2 | 1248 × 832 | 1290 |
| 3:4 | 864 x 1184 | 1290 |
| 4:3 | 1184 × 864 | 1290 |
| 4:5 | 896 × 1152 | 1290 |
| 5:4 | 1152 × 896 | 1290 |
| 9:16 | 768 × 1344 | 1290 |
| 16:9 | 1344 × 768 | 1290 |
| 21:9 | 1536 × 672 | 1290 |
Wann Imagen verwendet werden sollte
Imagen wurde eingestellt und ist nicht mehr über die Gemini API verfügbar. Nano Banana für die Bildgenerierung und ‑bearbeitung verwenden
Nächste Schritte
- Im Veo-Leitfaden erfahren Sie, wie Sie mit der Gemini API Videos generieren.
- Weitere Informationen zu Gemini-Modellen finden Sie unter Gemini-Modelle.