Nano Banana 图像生成
在 Google AI Studio 中体验
Nano Banana 是 Gemini 原生图像生成功能的名称。 Gemini 可以以文本、图像、视频或组合的方式生成和处理图像。这使您可以通过前所未有的控制来创建、编辑和迭代视觉效果。
选型 #
Nano Banana 是指 Gemini API 中提供的以下型号:
Nano Banana 2.1: 的 Gemini Nano Banana 2.1 型号(
gemini-nano-banana-2.1)。 Nano Banana 的更新 2, 作为图像生成和会话编辑的主要高效主力模型。它保持 Flash 级速度和成本效率,同时提供改进的视觉质量、文本渲染、多轮一致性以及 1K、2K 和 4K 分辨率的 Google 搜索事实依据。Nano Banana 2 Lite: 的 Gemini 3.1 Flash Lite Image 型号(
gemini-3.1-flash-lite-image)。最快、最便宜的 Gemini 图像模型,专为速度和规模而设计,其中速度和成本是主要限制。未针对多个参考输入或多轮顺序编辑进行优化。Nano Banana 2: 的 Gemini 3.1 Flash Image 型号(
gemini-3.1-flash-image)。上一代高效主力模型,针对速度、4K 生成和多个参考图像一致性进行了优化。建议所有新项目使用 Nano Banana 2.1.Nano Banana Pro: 的 Gemini 3 Pro Image 型号(
gemini-3-pro-image)。复杂视觉任务的优质选择,利用高级推理(“思维”)来遵循复杂的指令,保持品牌一致性并呈现高保真文本。Nano Banana: 的 Gemini 2.5 Flash Image 型号(
gemini-2.5-flash-image)。 Nano Banana 系列的旧型号。建议的迁移路径是 Nano Banana 2 Lite,以获得更高的质量、更快的速度和更低的价格。
所有生成的图像都包含 SynthID水印.
图像生成(文本到图像) #
from google import genai
from google.genai import types
from PIL import Image
client = genai.Client()
prompt = ("Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme")
response = client.models.generate_content(
model="gemini-nano-banana-2.1",
contents=[prompt],
)
for part in response.parts:
if part.text is not None:
print(part.text)
elif part.inline_data is not None:
image = part.as_image()
image.save("generated_image.png")
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 response = await ai.models.generateContent({
model: "gemini-nano-banana-2.1",
contents: prompt,
});
for (const part of response.candidates[0].content.parts) {
if (part.text) {
console.log(part.text);
} else if (part.inlineData) {
const imageData = part.inlineData.data;
const buffer = Buffer.from(imageData, "base64");
fs.writeFileSync("gemini-native-image.png", buffer);
console.log("Image saved as gemini-native-image.png");
}
}
}
main();
package main
import (
"context"
"fmt"
"log"
"os"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
result, _ := client.Models.GenerateContent(
ctx,
"gemini-nano-banana-2.1",
genai.Text("Create a picture of a nano banana dish in a " +
" fancy restaurant with a Gemini theme"),
nil,
)
for _, part := range result.Candidates[0].Content.Parts {
if part.Text != "" {
fmt.Println(part.Text)
} else if part.InlineData != nil {
imageBytes := part.InlineData.Data
outputFilename := "gemini_generated_image.png"
_ = os.WriteFile(outputFilename, imageBytes, 0644)
}
}
}
import com.google.genai.Client;
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.Part;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class TextToImage {
public static void main(String[] args) throws IOException {
try (Client client = new Client()) {
GenerateContentConfig config = GenerateContentConfig.builder()
.responseModalities("TEXT", "IMAGE")
.build();
GenerateContentResponse response = client.models.generateContent(
"gemini-nano-banana-2.1",
"Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme",
config);
for (Part part : response.parts()) {
if (part.text().isPresent()) {
System.out.println(part.text().get());
} else if (part.inlineData().isPresent()) {
var blob = part.inlineData().get();
if (blob.data().isPresent()) {
Files.write(Paths.get("_01_generated_image.png"), blob.data().get());
}
}
}
}
}
}
using Google.GenAI;
using Google.GenAI.Types;
using System;
using System.IO;
using System.Threading.Tasks;
public class TextToImage {
public static async Task Main(string[] args) {
var client = new Client();
var response = await client.Models.GenerateContentAsync(
model: "gemini-nano-banana-2.1",
contents: "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme"
);
foreach (var candidate in response.Candidates) {
foreach (var part in candidate.Content.Parts) {
if (part.Text != null) {
Console.WriteLine(part.Text);
} else if (part.InlineData != null) {
await File.WriteAllBytesAsync("generated_image.png", part.InlineData.Data);
Console.WriteLine("Image saved as generated_image.png");
}
}
}
}
}
curl -s -X POST \
"https://generativelanguage.googleapis.com/v1/models/gemini-nano-banana-2.1:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"contents": [{
"parts": [
{"text": "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme"}
]
}]
}'
图像编辑(文本和图像到图像) #
提醒:确保您对上传的任何图像拥有必要的权限。请勿生成侵犯他人权利的内容,包括欺骗、骚扰或伤害的视频或图像。您对这项生成式人工智能服务的使用须遵守我们的规定 禁止使用政策.
提供图像并使用文本提示来添加、删除或修改元素、更改样式或调整颜色分级。
下面的例子演示了上传 base64 编码图像。对于多个图像、更大的负载和支持的 MIME 类型,请检查 图像理解 页。
from google import genai
from google.genai import types
from PIL import Image
client = genai.Client()
prompt = (
"Create a picture of my cat eating a nano-banana in a "
"fancy restaurant under the Gemini constellation"
)
image = Image.open("/path/to/cat_image.png")
response = client.models.generate_content(
model="gemini-nano-banana-2.1",
contents=[prompt, image],
)
for part in response.parts:
if part.text is not None:
print(part.text)
elif part.inline_data is not None:
image = part.as_image()
image.save("generated_image.png")
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 = [
{ text: "Create a picture of my cat eating a nano-banana in a " +
"fancy restaurant under the Gemini constellation" },
{
inlineData: {
mimeType: "image/png",
data: base64Image,
},
},
];
const response = await ai.models.generateContent({
model: "gemini-nano-banana-2.1",
contents: prompt,
});
for (const part of response.candidates[0].content.parts) {
if (part.text) {
console.log(part.text);
} else if (part.inlineData) {
const imageData = part.inlineData.data;
const buffer = Buffer.from(imageData, "base64");
fs.writeFileSync("gemini-native-image.png", buffer);
console.log("Image saved as gemini-native-image.png");
}
}
}
main();
package main
import (
"context"
"fmt"
"log"
"os"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
imagePath := "/path/to/cat_image.png"
imgData, _ := os.ReadFile(imagePath)
parts := []*genai.Part{
genai.NewPartFromText("Create a picture of my cat eating a nano-banana in a fancy restaurant under the Gemini constellation"),
&genai.Part{
InlineData: &genai.Blob{
MIMEType: "image/png",
Data: imgData,
},
},
}
contents := []*genai.Content{
genai.NewContentFromParts(parts, genai.RoleUser),
}
result, _ := client.Models.GenerateContent(
ctx,
"gemini-nano-banana-2.1",
contents,
nil,
)
for _, part := range result.Candidates[0].Content.Parts {
if part.Text != "" {
fmt.Println(part.Text)
} else if part.InlineData != nil {
imageBytes := part.InlineData.Data
outputFilename := "gemini_generated_image.png"
_ = os.WriteFile(outputFilename, imageBytes, 0644)
}
}
}
import com.google.genai.Client;
import com.google.genai.types.Content;
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.Part;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class TextAndImageToImage {
public static void main(String[] args) throws IOException {
try (Client client = new Client()) {
GenerateContentConfig config = GenerateContentConfig.builder()
.responseModalities("TEXT", "IMAGE")
.build();
GenerateContentResponse response = client.models.generateContent(
"gemini-nano-banana-2.1",
Content.fromParts(
Part.fromText("""
Create a picture of my cat eating a nano-banana in
a fancy restaurant under the Gemini constellation
"""),
Part.fromBytes(
Files.readAllBytes(
Path.of("src/main/resources/cat.jpg")),
"image/jpeg")),
config);
for (Part part : response.parts()) {
if (part.text().isPresent()) {
System.out.println(part.text().get());
} else if (part.inlineData().isPresent()) {
var blob = part.inlineData().get();
if (blob.data().isPresent()) {
Files.write(Paths.get("gemini_generated_image.png"), blob.data().get());
}
}
}
}
}
}
using Google.GenAI;
using Google.GenAI.Types;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
public class TextAndImageToImage {
public static async Task Main(string[] args) {
var client = new Client();
var response = await client.Models.GenerateContentAsync(
model: "gemini-nano-banana-2.1",
contents: new Content
{
Parts = new List<Part>
{
new Part { Text = "Create a picture of my cat eating a nano-banana in a fancy restaurant under the Gemini constellation" },
Part.FromBytes(await File.ReadAllBytesAsync("/path/to/cat_image.png"), "image/png")
}
}
);
foreach (var candidate in response.Candidates) {
foreach (var part in candidate.Content.Parts) {
if (part.Text != null) {
Console.WriteLine(part.Text);
} else if (part.InlineData != null) {
await File.WriteAllBytesAsync("gemini_generated_image.png", part.InlineData.Data);
Console.WriteLine("Image saved as gemini_generated_image.png");
}
}
}
}
}
curl -s -X POST \
"https://generativelanguage.googleapis.com/v1/models/gemini-nano-banana-2.1:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d "{
\"contents\": [{
\"parts\":[
{\"text\": \"Create a picture of my cat eating a nano-banana in a fancy restaurant under the Gemini constellation\"},
{
\"inline_data\": {
\"mime_type\":\"image/jpeg\",
\"data\": \"<BASE64_IMAGE_DATA>\"
}
}
]
}]
}"
多轮图像编辑 #
继续以对话方式生成和编辑图像。聊天或多轮对话是迭代图像的推荐方式。以下示例显示生成有关光合作用的信息图的提示。
from google import genai
from google.genai import types
client = genai.Client()
chat = client.chats.create(
model="gemini-nano-banana-2.1",
config=types.GenerateContentConfig(
response_modalities=['TEXT', 'IMAGE'],
tools=[{"google_search": {}}]
)
)
message = "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."
response = chat.send_message(message)
for part in response.parts:
if part.text is not None:
print(part.text)
elif image:= part.as_image():
image.save("photosynthesis.png")
import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";
const ai = new GoogleGenAI({});
async function main() {
const chat = ai.chats.create({
model: "gemini-nano-banana-2.1",
config: {
responseModalities: ['TEXT', 'IMAGE'],
tools: [{googleSearch: {}}],
},
});
const message = "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."
let response = await chat.sendMessage({message});
for (const part of response.candidates[0].content.parts) {
if (part.text) {
console.log(part.text);
} else if (part.inlineData) {
const imageData = part.inlineData.data;
const buffer = Buffer.from(imageData, "base64");
fs.writeFileSync("photosynthesis.png", buffer);
console.log("Image saved as photosynthesis.png");
}
}
}
main();
package main
import (
"context"
"fmt"
"log"
"os"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
config := &genai.GenerateContentConfig{
ResponseModalities: []string{"TEXT", "IMAGE"},
Tools: []*genai.Tool{
{GoogleSearch: &genai.GoogleSearch{}},
},
}
chat, err := client.Chats.Create(ctx, "gemini-nano-banana-2.1", config, nil)
if err != nil {
log.Fatal(err)
}
message := "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."
resp, err := chat.SendMessage(ctx, genai.Part{Text: message})
if err != nil {
log.Fatal(err)
}
for _, part := range resp.Candidates[0].Content.Parts {
if part.Text != "" {
fmt.Println(part.Text)
} else if part.InlineData != nil {
err := os.WriteFile("photosynthesis.png", part.InlineData.Data, 0644)
if err != nil {
log.Fatal(err)
}
}
}
}
import com.google.genai.Chat;
import com.google.genai.Client;
import com.google.genai.types.Content;
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.GoogleSearch;
import com.google.genai.types.ImageConfig;
import com.google.genai.types.Part;
import com.google.genai.types.RetrievalConfig;
import com.google.genai.types.Tool;
import com.google.genai.types.ToolConfig;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class MultiturnImageEditing {
public static void main(String[] args) throws IOException {
try (Client client = new Client()) {
GenerateContentConfig config = GenerateContentConfig.builder()
.responseModalities("TEXT", "IMAGE")
.tools(Tool.builder()
.googleSearch(GoogleSearch.builder().build())
.build())
.build();
Chat chat = client.chats.create("gemini-nano-banana-2.1", config);
GenerateContentResponse response = chat.sendMessage("""
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.
""");
for (Part part : response.parts()) {
if (part.text().isPresent()) {
System.out.println(part.text().get());
} else if (part.inlineData().isPresent()) {
var blob = part.inlineData().get();
if (blob.data().isPresent()) {
Files.write(Paths.get("photosynthesis.png"), blob.data().get());
}
}
}
// ...
}
}
}
using Google.GenAI;
using Google.GenAI.Types;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
public class MultiturnImageEditing {
public static async Task Main(string[] args) {
var client = new Client();
var response = await client.Models.GenerateContentAsync(
model: "gemini-nano-banana-2.1",
contents: "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.",
config: new GenerateContentConfig
{
ResponseModalities = new List<string> { "TEXT", "IMAGE" },
Tools = new List<Tool> { new Tool { GoogleSearch = new GoogleSearch() } }
}
);
foreach (var candidate in response.Candidates) {
foreach (var part in candidate.Content.Parts) {
if (part.Text != null) {
Console.WriteLine(part.Text);
} else if (part.InlineData != null) {
await File.WriteAllBytesAsync("photosynthesis.png", part.InlineData.Data);
Console.WriteLine("Image saved as photosynthesis.png");
}
}
}
}
}
curl -s -X POST \
"https://generativelanguage.googleapis.com/v1/models/gemini-nano-banana-2.1:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"contents": [{
"role": "user",
"parts": [
{"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."}
]
}],
"generationConfig": {
"responseModalities": ["TEXT", "IMAGE"]
}
}'
然后,您可以使用相同的聊天将图形上的语言更改为西班牙语。
message = "Update this infographic to be in Spanish. Do not change any other elements of the image."
aspect_ratio = "16:9" # "1:1","1:4","1:8","2:3","3:2","3:4","4:1","4:3","4:5","5:4","8:1","9:16","16:9","21:9"
resolution = "2K" # "1K", "2K", "4K"
response = chat.send_message(message,
config=types.GenerateContentConfig(
image_config=types.ImageConfig(
aspect_ratio=aspect_ratio,
image_size=resolution
),
))
for part in response.parts:
if part.text is not None:
print(part.text)
elif image:= part.as_image():
image.save("photosynthesis_spanish.png")
const message = 'Update this infographic to be in Spanish. Do not change any other elements of the image.';
const aspectRatio = '16:9';
const resolution = '2K';
let response = await chat.sendMessage({
message,
config: {
responseModalities: ['TEXT', 'IMAGE'],
imageConfig: {
aspectRatio: aspectRatio,
imageSize: resolution,
},
tools: [{googleSearch: {}}],
},
});
for (const part of response.candidates[0].content.parts) {
if (part.text) {
console.log(part.text);
} else if (part.inlineData) {
const imageData = part.inlineData.data;
const buffer = Buffer.from(imageData, "base64");
fs.writeFileSync("photosynthesis2.png", buffer);
console.log("Image saved as photosynthesis2.png");
}
}
message = "Update this infographic to be in Spanish. Do not change any other elements of the image."
aspectRatio := "16:9" // "1:1","1:4","1:8","2:3","3:2","3:4","4:1","4:3","4:5","5:4","8:1","9:16","16:9","21:9"
resolution := "2K" // "1K", "2K", "4K"
config.ImageConfig = &genai.ImageConfig{
AspectRatio: aspectRatio,
ImageSize: resolution,
}
resp, err = chat.SendMessage(ctx, genai.Part{Text: message})
if err != nil {
log.Fatal(err)
}
for _, part := range resp.Candidates[0].Content.Parts {
if part.Text != "" {
fmt.Println(part.Text)
} else if part.InlineData != nil {
err := os.WriteFile("photosynthesis_spanish.png", part.InlineData.Data, 0644)
if err != nil {
log.Fatal(err)
}
}
}
String aspectRatio = "16:9"; // "1:1","1:4","1:8","2:3","3:2","3:4","4:1","4:3","4:5","5:4","8:1","9:16","16:9","21:9"
String resolution = "2K"; // "1K", "2K", "4K"
config = GenerateContentConfig.builder()
.responseModalities("TEXT", "IMAGE")
.imageConfig(ImageConfig.builder()
.aspectRatio(aspectRatio)
.imageSize(resolution)
.build())
.build();
response = chat.sendMessage(
"Update this infographic to be in Spanish. " +
"Do not change any other elements of the image.",
config);
for (Part part : response.parts()) {
if (part.text().isPresent()) {
System.out.println(part.text().get());
} else if (part.inlineData().isPresent()) {
var blob = part.inlineData().get();
if (blob.data().isPresent()) {
Files.write(Paths.get("photosynthesis_spanish.png"), blob.data().get());
}
}
}
using Google.GenAI;
using Google.GenAI.Types;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
public class MultiturnImageEditingSpanish {
public static async Task Main(string[] args) {
var client = new Client();
var response = await client.Models.GenerateContentAsync(
model: "gemini-nano-banana-2.1",
contents: new Content
{
Parts = new List<Part>
{
new Part { Text = "Update this infographic to be in Spanish. Do not change any other elements of the image." },
Part.FromBytes(await File.ReadAllBytesAsync("photosynthesis.png"), "image/png")
}
},
config: new GenerateContentConfig
{
ResponseModalities = new List<string> { "TEXT", "IMAGE" },
ImageConfig = new ImageConfig
{
AspectRatio = "16:9",
ImageSize = "2K"
}
}
);
foreach (var candidate in response.Candidates) {
foreach (var part in candidate.Content.Parts) {
if (part.Text != null) {
Console.WriteLine(part.Text);
} else if (part.InlineData != null) {
await File.WriteAllBytesAsync("photosynthesis_spanish.png", part.InlineData.Data);
Console.WriteLine("Image saved as photosynthesis_spanish.png");
}
}
}
}
}
curl -s -X POST \
"https://generativelanguage.googleapis.com/v1/models/gemini-nano-banana-2.1:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"contents": [
{
"role": "user",
"parts": [{"text": "Create a vibrant infographic that explains photosynthesis..."}]
},
{
"role": "model",
"parts": [{"inline_data": {"mime_type": "image/png", "data": "<PREVIOUS_IMAGE_DATA>"}}]
},
{
"role": "user",
"parts": [{"text": "Update this infographic to be in Spanish. Do not change any other elements of the image."}]
}
],
"tools": [{"google_search": {}}],
"generationConfig": {
"responseModalities": ["TEXT", "IMAGE"],
"imageConfig": {
"aspectRatio": "16:9",
"imageSize": "2K"
}
}
}'
## Nano Banana的特点
Nano Banana 型号提供最先进的图像生成和编辑功能。 Gemini Nano Banana 2.1 和 Gemini 3.1 Flash Image 针对速度和大批量用例进行了优化,Gemini 3 Pro Image 针对专业资产生产进行了优化。
它们旨在通过高级推理解决最具挑战性的工作流程,擅长复杂的多轮创建和修改任务。
高分辨率输出:1K、2K 和 4K 视觉效果的内置生成功能。
Gemini 3.1 Flash Image 添加了较小的 512 (0.5K) 分辨率(Gemini Nano Banana 2.1 不支持)。
高级文本渲染:能够为信息图表、菜单、图表和营销资产生成清晰的风格化文本。
使用 Google 搜索提供事实依据:该模型可以使用 Google 搜索作为工具来验证事实并根据实时数据(例如当前天气图、股票图表、最近事件)生成图像。
Gemini Nano Banana 2.1 和 Gemini 3.1 Flash Image 添加事实依据与 Google 搜索的集成,用于图像和 Web 搜索。
思维模式:该模型利用“思考”过程通过复杂的提示进行推理。它会生成临时“思想图像”(在后端可见但不收费),以在产生最终的高质量输出之前完善构图。
最多 14 参考图像:混合 14 参考图像以生成最终图像。
新的纵横比:Gemini Nano Banana 2.1 和 Gemini 3.1 Flash Image 添加 1:4, 4:1, 1:8, 和 8:1 纵横比.
最多使用 14 参考图像 #
Nano Banana 型号允许您混合 14 参考图像。这些 14 图像可以包含以下内容:
| Gemini Nano Banana 2.1 & Gemini 3.1 Flash Image | Gemini 3 Pro Image |
|---|---|
| 最终图像中包含高达 10 的高保真物体图像 | 最终图像中包含高达 6 的高保真物体图像 |
| 高达4的字符图像以保持字符一致性 | 高达5的字符图像以保持字符一致性 |
| N/A | 最多 3 图像可用作样式参考 |
from google import genai
from google.genai import types
from PIL import Image
prompt = "An office group photo of these people, they are making funny faces."
aspect_ratio = "5:4" # "1:1","1:4","1:8","2:3","3:2","3:4","4:1","4:3","4:5","5:4","8:1","9:16","16:9","21:9"
resolution = "2K" # "1K", "2K", "4K"
client = genai.Client()
response = client.models.generate_content(
model="gemini-nano-banana-2.1",
contents=[
prompt,
Image.open('person1.png'),
Image.open('person2.png'),
Image.open('person3.png'),
Image.open('person4.png'),
Image.open('person5.png'),
],
config=types.GenerateContentConfig(
response_modalities=['TEXT', 'IMAGE'],
image_config=types.ImageConfig(
aspect_ratio=aspect_ratio,
image_size=resolution
),
)
)
for part in response.parts:
if part.text is not None:
print(part.text)
elif image:= part.as_image():
image.save("office.png")
import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";
async function main() {
const ai = new GoogleGenAI({});
const prompt =
'An office group photo of these people, they are making funny faces.';
const aspectRatio = '5:4';
const resolution = '2K';
const base64ImageFile1 = fs.readFileSync("person1.png", { encoding: "base64" });
const base64ImageFile2 = fs.readFileSync("person2.png", { encoding: "base64" });
const base64ImageFile3 = fs.readFileSync("person3.png", { encoding: "base64" });
const base64ImageFile4 = fs.readFileSync("person4.png", { encoding: "base64" });
const base64ImageFile5 = fs.readFileSync("person5.png", { encoding: "base64" });
const contents = [
{ text: prompt },
{
inlineData: {
mimeType: "image/jpeg",
data: base64ImageFile1,
},
},
{
inlineData: {
mimeType: "image/jpeg",
data: base64ImageFile2,
},
},
{
inlineData: {
mimeType: "image/jpeg",
data: base64ImageFile3,
},
},
{
inlineData: {
mimeType: "image/jpeg",
data: base64ImageFile4,
},
},
{
inlineData: {
mimeType: "image/jpeg",
data: base64ImageFile5,
},
}
];
const response = await ai.models.generateContent({
model: 'gemini-nano-banana-2.1',
contents: contents,
config: {
responseModalities: ['TEXT', 'IMAGE'],
imageConfig: {
aspectRatio: aspectRatio,
imageSize: resolution,
},
},
});
for (const part of response.candidates[0].content.parts) {
if (part.text) {
console.log(part.text);
} else if (part.inlineData) {
const imageData = part.inlineData.data;
const buffer = Buffer.from(imageData, "base64");
fs.writeFileSync("image.png", buffer);
console.log("Image saved as image.png");
}
}
}
main();
package main
import (
"context"
"fmt"
"log"
"os"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
config := &genai.GenerateContentConfig{
ResponseModalities: []string{"TEXT", "IMAGE"},
ImageConfig: &genai.ImageConfig{
AspectRatio: "5:4",
ImageSize: "2K",
},
}
img1, err := os.ReadFile("person1.png")
if err != nil { log.Fatal(err) }
img2, err := os.ReadFile("person2.png")
if err != nil { log.Fatal(err) }
img3, err := os.ReadFile("person3.png")
if err != nil { log.Fatal(err) }
img4, err := os.ReadFile("person4.png")
if err != nil { log.Fatal(err) }
img5, err := os.ReadFile("person5.png")
if err != nil { log.Fatal(err) }
parts := []*genai.Part{
genai.NewPartFromText("An office group photo of these people, they are making funny faces."),
&genai.Part{InlineData: &genai.Blob{MIMEType: "image/png", Data: img1}},
&genai.Part{InlineData: &genai.Blob{MIMEType: "image/png", Data: img2}},
&genai.Part{InlineData: &genai.Blob{MIMEType: "image/png", Data: img3}},
&genai.Part{InlineData: &genai.Blob{MIMEType: "image/png", Data: img4}},
&genai.Part{InlineData: &genai.Blob{MIMEType: "image/png", Data: img5}},
}
contents := []*genai.Content{
genai.NewContentFromParts(parts, genai.RoleUser),
}
resp, err := client.Models.GenerateContent(ctx, "gemini-nano-banana-2.1", contents, config)
if err != nil {
log.Fatal(err)
}
for _, part := range resp.Candidates[0].Content.Parts {
if part.Text != "" {
fmt.Println(part.Text)
} else if part.InlineData != nil {
err := os.WriteFile("office.png", part.InlineData.Data, 0644)
if err != nil {
log.Fatal(err)
}
}
}
}
import com.google.genai.Client;
import com.google.genai.types.Content;
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.ImageConfig;
import com.google.genai.types.Part;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class GroupPhoto {
public static void main(String[] args) throws IOException {
try (Client client = new Client()) {
GenerateContentConfig config = GenerateContentConfig.builder()
.responseModalities("TEXT", "IMAGE")
.imageConfig(ImageConfig.builder()
.aspectRatio("5:4")
.imageSize("2K")
.build())
.build();
GenerateContentResponse response = client.models.generateContent(
"gemini-nano-banana-2.1",
Content.fromParts(
Part.fromText("An office group photo of these people, they are making funny faces."),
Part.fromBytes(Files.readAllBytes(Path.of("person1.png")), "image/png"),
Part.fromBytes(Files.readAllBytes(Path.of("person2.png")), "image/png"),
Part.fromBytes(Files.readAllBytes(Path.of("person3.png")), "image/png"),
Part.fromBytes(Files.readAllBytes(Path.of("person4.png")), "image/png"),
Part.fromBytes(Files.readAllBytes(Path.of("person5.png")), "image/png")
), config);
for (Part part : response.parts()) {
if (part.text().isPresent()) {
System.out.println(part.text().get());
} else if (part.inlineData().isPresent()) {
var blob = part.inlineData().get();
if (blob.data().isPresent()) {
Files.write(Paths.get("office.png"), blob.data().get());
}
}
}
}
}
}
using Google.GenAI;
using Google.GenAI.Types;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
public class GroupPhoto {
public static async Task Main(string[] args) {
var client = new Client();
var response = await client.Models.GenerateContentAsync(
model: "gemini-nano-banana-2.1",
contents: new Content
{
Parts = new List<Part>
{
new Part { Text = "An office group photo of these people, they are making funny faces." },
Part.FromBytes(await File.ReadAllBytesAsync("person1.png"), "image/png"),
Part.FromBytes(await File.ReadAllBytesAsync("person2.png"), "image/png"),
Part.FromBytes(await File.ReadAllBytesAsync("person3.png"), "image/png"),
Part.FromBytes(await File.ReadAllBytesAsync("person4.png"), "image/png"),
Part.FromBytes(await File.ReadAllBytesAsync("person5.png"), "image/png")
}
},
config: new GenerateContentConfig
{
ResponseModalities = new List<string> { "TEXT", "IMAGE" },
ImageConfig = new ImageConfig
{
AspectRatio = "5:4",
ImageSize = "2K"
}
}
);
foreach (var candidate in response.Candidates) {
foreach (var part in candidate.Content.Parts) {
if (part.Text != null) {
Console.WriteLine(part.Text);
} else if (part.InlineData != null) {
await File.WriteAllBytesAsync("office.png", part.InlineData.Data);
Console.WriteLine("Image saved as office.png");
}
}
}
}
}
curl -s -X POST \
"https://generativelanguage.googleapis.com/v1/models/gemini-nano-banana-2.1:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d "{
\"contents\": [{
\"parts\":[
{\"text\": \"An office group photo of these people, they are making funny faces.\"},
{\"inline_data\": {\"mime_type\":\"image/png\", \"data\": \"<BASE64_DATA_IMG_1>\"}},
{\"inline_data\": {\"mime_type\":\"image/png\", \"data\": \"<BASE64_DATA_IMG_2>\"}},
{\"inline_data\": {\"mime_type\":\"image/png\", \"data\": \"<BASE64_DATA_IMG_3>\"}},
{\"inline_data\": {\"mime_type\":\"image/png\", \"data\": \"<BASE64_DATA_IMG_4>\"}},
{\"inline_data\": {\"mime_type\":\"image/png\", \"data\": \"<BASE64_DATA_IMG_5>\"}}
]
}],
\"generationConfig\": {
\"responseModalities\": [\"TEXT\", \"IMAGE\"],
\"imageConfig\": {
\"aspectRatio\": \"5:4\",
\"imageSize\": \"2K\"
}
}
}"
### 事实依据与 Google 搜索
使用 Google 搜索工具 根据实时信息(例如天气预报、股票图表或最近的事件)生成图像。
请注意,当将事实依据与 Google 搜索与图像生成结合使用时,基于图像的搜索结果不会传递到生成模型,并且会从响应中排除(请参阅 事实依据和 Google 搜索用于图像).
from google import genai
from google.genai import types
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"
aspect_ratio = "16:9" # "1:1","1:4","1:8","2:3","3:2","3:4","4:1","4:3","4:5","5:4","8:1","9:16","16:9","21:9"
client = genai.Client()
response = client.models.generate_content(
model="gemini-nano-banana-2.1",
contents=prompt,
config=types.GenerateContentConfig(
response_modalities=['Text', 'Image'],
image_config=types.ImageConfig(
aspect_ratio=aspect_ratio,
),
tools=[{"google_search": {}}]
)
)
for part in response.parts:
if part.text is not None:
print(part.text)
elif image:= part.as_image():
image.save("weather.png")
import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";
async function main() {
const ai = new GoogleGenAI({});
const 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';
const aspectRatio = '16:9';
const resolution = '2K';
const response = await ai.models.generateContent({
model: 'gemini-nano-banana-2.1',
contents: prompt,
config: {
responseModalities: ['TEXT', 'IMAGE'],
imageConfig: {
aspectRatio: aspectRatio,
imageSize: resolution,
},
tools: [{ googleSearch: {} }]
},
});
for (const part of response.candidates[0].content.parts) {
if (part.text) {
console.log(part.text);
} else if (part.inlineData) {
const imageData = part.inlineData.data;
const buffer = Buffer.from(imageData, "base64");
fs.writeFileSync("image.png", buffer);
console.log("Image saved as image.png");
}
}
}
main();
import com.google.genai.Client;
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.GoogleSearch;
import com.google.genai.types.ImageConfig;
import com.google.genai.types.Part;
import com.google.genai.types.Tool;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class SearchGrounding {
public static void main(String[] args) throws IOException {
try (Client client = new Client()) {
GenerateContentConfig config = GenerateContentConfig.builder()
.responseModalities("TEXT", "IMAGE")
.imageConfig(ImageConfig.builder()
.aspectRatio("16:9")
.build())
.tools(Tool.builder()
.googleSearch(GoogleSearch.builder().build())
.build())
.build();
GenerateContentResponse response = client.models.generateContent(
"gemini-nano-banana-2.1", """
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
""",
config);
for (Part part : response.parts()) {
if (part.text().isPresent()) {
System.out.println(part.text().get());
} else if (part.inlineData().isPresent()) {
var blob = part.inlineData().get();
if (blob.data().isPresent()) {
Files.write(Paths.get("weather.png"), blob.data().get());
}
}
}
}
}
}
using Google.GenAI;
using Google.GenAI.Types;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
public class SearchGrounding {
public static async Task Main(string[] args) {
var client = new Client();
var response = await client.Models.GenerateContentAsync(
model: "gemini-nano-banana-2.1",
contents: "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",
config: new GenerateContentConfig
{
ResponseModalities = new List<string> { "TEXT", "IMAGE" },
ImageConfig = new ImageConfig
{
AspectRatio = "16:9"
},
Tools = new List<Tool> { new Tool { GoogleSearch = new GoogleSearch() } }
}
);
foreach (var candidate in response.Candidates) {
foreach (var part in candidate.Content.Parts) {
if (part.Text != null) {
Console.WriteLine(part.Text);
} else if (part.InlineData != null) {
await File.WriteAllBytesAsync("weather.png", part.InlineData.Data);
Console.WriteLine("Image saved as weather.png");
}
}
}
}
}
curl -s -X POST \
"https://generativelanguage.googleapis.com/v1/models/gemini-nano-banana-2.1:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"contents": [{"parts": [{"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": [{"google_search": {}}],
"generationConfig": {
"responseModalities": ["TEXT", "IMAGE"],
"imageConfig": {
"aspectRatio": "16:9"
}
}
}'
响应包括 groundingMetadata 其中包含以下必填字段:
searchEntryPoint:包含用于呈现所需搜索建议的 HTML 和 CSS。groundingChunks:返回用于生成图像的顶级 3 Web 源
事实依据和 Google 搜索用于图像(Nano Banana 2.1 和 3.1 Flash) #
用于图像的事实依据和 Google 搜索允许模型使用通过 Google 搜索检索的 Web 图像作为图像生成的视觉上下文。图像搜索是现有事实依据和 Google 搜索工具中的一种新搜索类型,与标准功能一起运行 网页搜索.
要启用图像搜索,请配置 googleSearch 您的 API 请求中的工具并指定 imageSearch 内 searchTypes 对象。图像搜索可以单独使用,也可以与网页搜索一起使用。
请注意,图像的事实依据和 Google 搜索不能用于搜索人员。
from google import genai
from google.genai import types
from IPython.display import display, HTML
prompt = "A detailed painting of a Timareta butterfly resting on a flower"
client = genai.Client()
response = client.models.generate_content(
model="gemini-nano-banana-2.1",
contents=prompt,
config=types.GenerateContentConfig(
response_modalities=["IMAGE"],
tools=[
types.Tool(google_search=types.GoogleSearch(
search_types=types.SearchTypes(
web_search=types.WebSearch(),
image_search=types.ImageSearch()
)
))
]
)
)
# Display grounding sources if available
if response.candidates and response.candidates[0].grounding_metadata and response.candidates[0].grounding_metadata.search_entry_point:
display(HTML(response.candidates[0].grounding_metadata.search_entry_point.rendered_content))
import { GoogleGenAI } from "@google/genai";
async function main() {
const ai = new GoogleGenAI({});
const prompt = "A detailed painting of a Timareta butterfly resting on a flower";
const response = await ai.models.generateContent({
model: "gemini-nano-banana-2.1",
contents: prompt,
config: {
responseModalities: ["IMAGE"],
tools: [
{
googleSearch: {
searchTypes: {
webSearch: {},
imageSearch: {}
}
}
}
]
}
});
// Display grounding sources if available
if (response.candidates && response.candidates[0].groundingMetadata && response.candidates[0].groundingMetadata.searchEntryPoint) {
console.log(response.candidates[0].groundingMetadata.searchEntryPoint.renderedContent);
}
}
main();
package main
import (
"context"
"fmt"
"log"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
config := &genai.GenerateContentConfig{
ResponseModalities: []string{"IMAGE"},
Tools: []*genai.Tool{
{
GoogleSearch: &genai.GoogleSearch{
SearchTypes: &genai.SearchTypes{
WebSearch: &genai.WebSearch{},
ImageSearch: &genai.ImageSearch{},
},
},
},
},
}
prompt := "A detailed painting of a Timareta butterfly resting on a flower"
resp, err := client.Models.GenerateContent(ctx, "gemini-nano-banana-2.1", genai.Text(prompt), config)
if err != nil {
log.Fatal(err)
}
if resp.Candidates[0].GroundingMetadata != nil && resp.Candidates[0].GroundingMetadata.SearchEntryPoint != nil {
fmt.Println(resp.Candidates[0].GroundingMetadata.SearchEntryPoint.RenderedContent)
}
}
import com.google.genai.Client;
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.GoogleSearch;
import com.google.genai.types.ImageSearch;
import com.google.genai.types.SearchTypes;
import com.google.genai.types.Tool;
import com.google.genai.types.WebSearch;
import java.io.IOException;
public class ImageSearchGrounding {
public static void main(String[] args) throws IOException {
try (Client client = new Client()) {
GenerateContentConfig config = GenerateContentConfig.builder()
.responseModalities("IMAGE")
.tools(Tool.builder()
.googleSearch(GoogleSearch.builder()
.searchTypes(SearchTypes.builder()
.webSearch(WebSearch.builder().build())
.imageSearch(ImageSearch.builder().build())
.build())
.build())
.build())
.build();
GenerateContentResponse response = client.models.generateContent(
"gemini-nano-banana-2.1",
"A detailed painting of a Timareta butterfly resting on a flower",
config);
if (response.candidates().isPresent() && !response.candidates().get().isEmpty()) {
var candidate = response.candidates().get().get(0);
if (candidate.groundingMetadata().isPresent() && candidate.groundingMetadata().get().searchEntryPoint().isPresent()) {
System.out.println(candidate.groundingMetadata().get().searchEntryPoint().get().renderedContent().orElse(""));
}
}
}
}
}
using Google.GenAI;
using Google.GenAI.Types;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
public class ImageSearchGrounding {
public static async Task Main(string[] args) {
var client = new Client();
var response = await client.Models.GenerateContentAsync(
model: "gemini-nano-banana-2.1",
contents: "A detailed painting of a Timareta butterfly resting on a flower",
config: new GenerateContentConfig
{
ResponseModalities = new List<string> { "IMAGE" },
Tools = new List<Tool>
{
new Tool
{
GoogleSearch = new GoogleSearch
{
SearchTypes = new SearchTypes
{
WebSearch = new WebSearch(),
ImageSearch = new ImageSearch()
}
}
}
}
}
);
foreach (var candidate in response.Candidates) {
if (candidate.GroundingMetadata != null && candidate.GroundingMetadata.SearchEntryPoint != null) {
Console.WriteLine(candidate.GroundingMetadata.SearchEntryPoint.RenderedContent);
}
}
}
}
curl -s -X POST \
"https://generativelanguage.googleapis.com/v1/models/gemini-nano-banana-2.1:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"contents": [{"parts": [{"text": "A detailed painting of a Timareta butterfly resting on a flower"}]}],
"tools": [{"google_search": {"searchTypes": {"webSearch": {}, "imageSearch": {}}}}],
"generationConfig": {
"responseModalities": ["IMAGE"]
}
}'
显示要求
当您在事实依据中使用图像搜索与 Google 搜索时,必须遵守以下条件:
来源归属:您必须以用户能够识别为链接的方式提供包含源图像的网页(“包含页面”,而不是图像文件本身)的链接。
直接导航:如果您还选择显示源图像,则必须提供从源图像到其包含的源网页的直接单击路径。不允许延迟或抽象最终用户对源网页的访问的任何其他实现,包括但不限于任何多次点击路径或中间图像查看器的使用。
回应
对于使用图像搜索的提供事实依据响应,API 提供明确的归属和元数据,将其输出链接到经过验证的来源。中的关键字段 groundingMetadata 对象包括:
imageSearchQueries:模型用于视觉上下文(图像搜索)的特定查询。groundingChunks:包含检索结果的源信息。对于图像源,这些将使用新的图像块类型作为重定向 URL 返回。该块包括:uri:归因的网页 URL(登陆页面)。image_uri:直接图像 URL。groundingSupports:提供将生成的内容链接到块中的相关引用源的特定映射。searchEntryPoint:包括“Google 搜索”芯片,其中包含兼容的 HTML 和 CSS,用于呈现搜索建议。
视频到图像生成(Nano Banana 2.1, 3.1 Flash 和 3.1 Flash Lite) #
视频到图像生成允许您使用视频上下文作为多模态参考来生成新图像。这对于创建高质量视频缩略图、电影海报、摘要信息图或受视频场景启发的新艺术作品非常有用。
在生成过程中,模型会分析上下文中的视频帧(最高可达模型的输入 131,072 token 的 token 限制)以提取视觉主题和关键事件,然后将它们与文本提示一起使用来合成输出图像。
你可以通过公共 YouTube 网址 直接在您的 API 请求中或使用以下命令上传本地视频文件 Files API.
from google import genai
from google.genai import types
client = genai.Client()
# Pass a public YouTube video URL as part of the contents
response = client.models.generate_content(
model="gemini-nano-banana-2.1",
contents=[
types.Part(
file_data=types.FileData(file_uri="https://www.youtube.com/watch?v=UTdfxFyOQTI"),
video_metadata=types.VideoMetadata(fps=0.5)
),
"Generate a poster image that captures the key themes of this video."
],
config=types.GenerateContentConfig(
response_modalities=["TEXT", "IMAGE"]
)
)
# Save the generated image part
for part in response.parts:
if part.inline_data is not None:
image = part.as_image()
image.save("video_poster.png")
print("Image saved as video_poster.png")
import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";
async function main() {
const ai = new GoogleGenAI({});
const response = await ai.models.generateContent({
model: "gemini-nano-banana-2.1",
contents: [
{
fileData: {
fileUri: "https://www.youtube.com/watch?v=UTdfxFyOQTI",
},
videoMetadata: {
fps: 0.5
}
},
{ text: "Generate a poster image that captures the key themes of this video." }
],
config: {
responseModalities: ["TEXT", "IMAGE"]
}
});
for (const part of response.candidates[0].content.parts) {
if (part.inlineData) {
const imageData = part.inlineData.data;
const buffer = Buffer.from(imageData, "base64");
fs.writeFileSync("video_poster.png", buffer);
console.log("Image saved as video_poster.png");
}
}
}
main();
package main
import (
"context"
"log"
"os"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
videoPart := genai.NewPartFromURI("https://www.youtube.com/watch?v=UTdfxFyOQTI", "video/mp4")
videoPart.VideoMetadata = &genai.VideoMetadata{FPS: genai.Ptr(0.5)}
parts := []*genai.Part{
videoPart,
genai.NewPartFromText("Generate a poster image that captures the key themes of this video."),
}
contents := []*genai.Content{
genai.NewContentFromParts(parts, genai.RoleUser),
}
result, err := client.Models.GenerateContent(
ctx,
"gemini-nano-banana-2.1",
contents,
&genai.GenerateContentConfig{
ResponseModalities: []string{"TEXT", "IMAGE"},
},
)
if err != nil {
log.Fatal(err)
}
for _, part := range result.Candidates[0].Content.Parts {
if part.InlineData != nil {
imageBytes := part.InlineData.Data
_ = os.WriteFile("video_poster.png", imageBytes, 0644)
log.Println("Image saved as video_poster.png")
}
}
}
import com.google.genai.Client;
import com.google.genai.types.Content;
import com.google.genai.types.FileData;
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.Part;
import com.google.genai.types.VideoMetadata;
import com.google.common.collect.ImmutableList;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class VideoToImage {
public static void main(String[] args) throws IOException {
try (Client client = new Client()) {
Part videoPart = Part.builder()
.fileData(FileData.builder()
.fileUri("https://www.youtube.com/watch?v=UTdfxFyOQTI")
.build())
.videoMetadata(VideoMetadata.builder()
.fps(0.5)
.build())
.build();
Part textPart = Part.builder()
.text("Generate a poster image that captures the key themes of this video.")
.build();
GenerateContentConfig config = GenerateContentConfig.builder()
.responseModalities("TEXT", "IMAGE")
.build();
GenerateContentResponse response = client.models.generateContent(
"gemini-nano-banana-2.1",
Content.builder()
.role("user")
.parts(ImmutableList.of(videoPart, textPart))
.build(),
config);
for (Part part : response.parts()) {
if (part.inlineData().isPresent()) {
var blob = part.inlineData().get();
if (blob.data().isPresent()) {
Files.write(Paths.get("video_poster.png"), blob.data().get());
System.out.println("Image saved as video_poster.png");
}
}
}
}
}
}
using Google.GenAI;
using Google.GenAI.Types;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
public class VideoToImage {
public static async Task Main(string[] args) {
var client = new Client();
var response = await client.Models.GenerateContentAsync(
model: "gemini-nano-banana-2.1",
contents: new Content
{
Parts = new List<Part>
{
new Part
{
FileData = new FileData { FileUri = "https://www.youtube.com/watch?v=UTdfxFyOQTI" },
VideoMetadata = new VideoMetadata { Fps = 0.5 }
},
new Part { Text = "Generate a poster image that captures the key themes of this video." }
}
},
config: new GenerateContentConfig
{
ResponseModalities = new List<string> { "TEXT", "IMAGE" }
}
);
foreach (var candidate in response.Candidates) {
foreach (var part in candidate.Content.Parts) {
if (part.InlineData != null) {
await File.WriteAllBytesAsync("video_poster.png", part.InlineData.Data);
Console.WriteLine("Image saved as video_poster.png");
}
}
}
}
}
curl -s -X POST \
"https://generativelanguage.googleapis.com/v1/models/gemini-nano-banana-2.1:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"contents": [{
"parts": [
{
"file_data": {
"file_uri": "https://www.youtube.com/watch?v=UTdfxFyOQTI"
},
"video_metadata": {
"fps": 0.5
}
},
{"text": "Generate a poster image that captures the key themes of this video."}
]
}],
"generationConfig": {
"responseModalities": ["TEXT", "IMAGE"]
}
}'
### 生成高达 4K 分辨率的图像
Gemini 3图像模型默认生成1K图像,但也可以输出2K、4K和512(0.5K)(仅限Gemini 3.1 Flash Image)图像。要生成更高分辨率的资源,请指定 image_size 在 generation_config.
您必须使用大写“K”(例如 1K、2K、4K)。的 512 值不使用“K”后缀。小写参数(例如 1k)将被拒绝。
from google import genai
from google.genai import types
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."
aspect_ratio = "1:1" # "1:1","1:4","1:8","2:3","3:2","3:4","4:1","4:3","4:5","5:4","8:1","9:16","16:9","21:9"
resolution = "1K" # "1K", "2K", "4K"
client = genai.Client()
response = client.models.generate_content(
model="gemini-nano-banana-2.1",
contents=prompt,
config=types.GenerateContentConfig(
response_modalities=['TEXT', 'IMAGE'],
image_config=types.ImageConfig(
aspect_ratio=aspect_ratio,
image_size=resolution
),
)
)
for part in response.parts:
if part.text is not None:
print(part.text)
elif image:= part.as_image():
image.save("butterfly.png")
import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";
async function main() {
const ai = new GoogleGenAI({});
const 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.';
const aspectRatio = '1:1';
const resolution = '1K';
const response = await ai.models.generateContent({
model: 'gemini-nano-banana-2.1',
contents: prompt,
config: {
responseModalities: ['TEXT', 'IMAGE'],
imageConfig: {
aspectRatio: aspectRatio,
imageSize: resolution,
},
},
});
for (const part of response.candidates[0].content.parts) {
if (part.text) {
console.log(part.text);
} else if (part.inlineData) {
const imageData = part.inlineData.data;
const buffer = Buffer.from(imageData, "base64");
fs.writeFileSync("butterfly.png", buffer);
console.log("Image saved as butterfly.png");
}
}
}
main();
package main
import (
"context"
"fmt"
"log"
"os"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
config := &genai.GenerateContentConfig{
ResponseModalities: []string{"TEXT", "IMAGE"},
ImageConfig: &genai.ImageConfig{
AspectRatio: "1:1",
ImageSize: "1K",
},
}
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."
resp, err := client.Models.GenerateContent(
ctx,
"gemini-nano-banana-2.1",
genai.Text(prompt),
config,
)
if err != nil {
log.Fatal(err)
}
for _, part := range resp.Candidates[0].Content.Parts {
if part.Text != "" {
fmt.Println(part.Text)
} else if part.InlineData != nil {
err := os.WriteFile("butterfly.png", part.InlineData.Data, 0644)
if err != nil {
log.Fatal(err)
}
}
}
}
import com.google.genai.Client;
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.ImageConfig;
import com.google.genai.types.Part;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class HiRes {
public static void main(String[] args) throws IOException {
try (Client client = new Client()) {
GenerateContentConfig config = GenerateContentConfig.builder()
.responseModalities("TEXT", "IMAGE")
.imageConfig(ImageConfig.builder()
.aspectRatio("1:1")
.imageSize("1K")
.build())
.build();
GenerateContentResponse response = client.models.generateContent(
"gemini-nano-banana-2.1", """
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.
""",
config);
for (Part part : response.parts()) {
if (part.text().isPresent()) {
System.out.println(part.text().get());
} else if (part.inlineData().isPresent()) {
var blob = part.inlineData().get();
if (blob.data().isPresent()) {
Files.write(Paths.get("butterfly.png"), blob.data().get());
}
}
}
}
}
}
using Google.GenAI;
using Google.GenAI.Types;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
public class HiRes {
public static async Task Main(string[] args) {
var client = new Client();
var response = await client.Models.GenerateContentAsync(
model: "gemini-nano-banana-2.1",
contents: "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.",
config: new GenerateContentConfig
{
ResponseModalities = new List<string> { "TEXT", "IMAGE" },
ImageConfig = new ImageConfig
{
AspectRatio = "1:1",
ImageSize = "1K"
}
}
);
foreach (var candidate in response.Candidates) {
foreach (var part in candidate.Content.Parts) {
if (part.Text != null) {
Console.WriteLine(part.Text);
} else if (part.InlineData?.Data != null) {
await File.WriteAllBytesAsync("butterfly.png", part.InlineData.Data);
Console.WriteLine("Image saved as butterfly.png");
}
}
}
}
}
curl -s -X POST \
"https://generativelanguage.googleapis.com/v1/models/gemini-nano-banana-2.1:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"contents": [{"parts": [{"text": "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."}]}],
"generationConfig": {
"responseModalities": ["TEXT", "IMAGE"],
"imageConfig": {
"aspectRatio": "1:1",
"imageSize": "1K"
}
}
}'
以下是根据此提示生成的示例图像:
### 思考过程
Gemini 3 图像模型是思维模型,使用推理过程(“思维”)来处理复杂的提示。该功能默认启用,且在 API 中无法禁用。要了解有关思考过程的更多信息,请参阅 Gemini 思考能力 指导。
该模型生成最多两个临时图像来测试构图和逻辑。 Thinking 中的最后一个图像也是最终渲染的图像。
您可以检查导致生成最终图像的想法。
for part in response.parts:
if part.thought:
if part.text:
print(part.text)
elif image:= part.as_image():
image.show()
for (const part of response.candidates[0].content.parts) {
if (part.thought) {
if (part.text) {
console.log(part.text);
} else if (part.inlineData) {
const imageData = part.inlineData.data;
const buffer = Buffer.from(imageData, 'base64');
fs.writeFileSync('image.png', buffer);
console.log('Image saved as image.png');
}
}
}
for (Part part : response.parts()) {
if (part.thought().orElse(false)) {
if (part.text().isPresent()) {
System.out.println(part.text().get());
} else if (part.inlineData().isPresent()) {
var blob = part.inlineData().get();
if (blob.data().isPresent()) {
Files.write(Paths.get("image.png"), blob.data().get());
System.out.println("Image saved as image.png");
}
}
}
}
foreach (var candidate in response.Candidates) {
foreach (var part in candidate.Content.Parts) {
if (part.Thought == true) {
if (part.Text != null) {
Console.WriteLine(part.Text);
} else if (part.InlineData?.Data != null) {
await File.WriteAllBytesAsync("image.png", part.InlineData.Data);
Console.WriteLine("Image saved as image.png");
}
}
}
}
控制思维水平 #
使用 Gemini Nano Banana 2.1、Gemini 3.1 Flash Image 和 Gemini 3.1 Flash Lite Image,您可以控制模型用于平衡质量和延迟的思考量:
| 模型 | 支持的思维水平 | 默认 |
|---|---|---|
| Gemini Nano Banana 2.1 | minimal, medium, high | medium |
| Gemini 3.1 Flash Image | minimal, high | minimal |
| Gemini 3.1 Flash Lite Image | minimal, high | minimal |
设置 thinkingLevel 到 minimal 提供最低的延迟响应。请注意,最少思考并不意味着模型根本不使用思考。
您可以添加 includeThoughts 布尔值以确定模型生成的想法是在响应中返回还是保持隐藏。
from google import genai
from google.genai import types
client = genai.Client()
response = client.models.generate_content(
model="gemini-nano-banana-2.1",
contents="A futuristic city built inside a giant glass bottle floating in space",
config=types.GenerateContentConfig(
response_modalities=["IMAGE"],
thinking_config=types.ThinkingConfig(
thinking_level="High",
include_thoughts=True
),
)
)
for part in response.parts:
if part.thought: # Skip outputting thoughts
continue
if part.text:
print(part.text)
elif image := part.as_image():
image.save("image.png")
import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";
async function main() {
const ai = new GoogleGenAI({});
const response = await ai.models.generateContent({
model: "gemini-nano-banana-2.1",
contents: "A futuristic city built inside a giant glass bottle floating in space",
config: {
responseModalities: ["IMAGE"],
thinkingConfig: {
thinkingLevel: "High",
includeThoughts: true
},
},
});
for (const part of response.candidates[0].content.parts) {
if (part.thought) { // Skip outputting thoughts
continue;
}
if (part.text) {
console.log(part.text);
} else if (part.inlineData) {
const imageData = part.inlineData.data;
const buffer = Buffer.from(imageData, "base64");
fs.writeFileSync("image.png", buffer);
console.log("Image saved as image.png");
}
}
}
main();
package main
import (
"context"
"fmt"
"log"
"os"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
config := &genai.GenerateContentConfig{
ResponseModalities: []string{"IMAGE"},
ThinkingConfig: &genai.ThinkingConfig{
ThinkingLevel: genai.ThinkingLevelHigh,
IncludeThoughts: true,
},
}
prompt := "A futuristic city built inside a giant glass bottle floating in space"
resp, err := client.Models.GenerateContent(
ctx,
"gemini-nano-banana-2.1",
genai.Text(prompt),
config,
)
if err != nil {
log.Fatal(err)
}
for _, part := range resp.Candidates[0].Content.Parts {
if part.Thought { // Skip outputting thoughts
continue
}
if part.Text != "" {
fmt.Println(part.Text)
} else if part.InlineData != nil {
err := os.WriteFile("image.png", part.InlineData.Data, 0644)
if err != nil {
log.Fatal(err)
}
}
}
}
import com.google.genai.Client;
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.Part;
import com.google.genai.types.ThinkingConfig;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class ThinkingLevels {
public static void main(String[] args) throws IOException {
try (Client client = new Client()) {
GenerateContentConfig config = GenerateContentConfig.builder()
.responseModalities("IMAGE")
.thinkingConfig(ThinkingConfig.builder()
.thinkingLevel("High")
.includeThoughts(true)
.build())
.build();
GenerateContentResponse response = client.models.generateContent(
"gemini-nano-banana-2.1",
"A futuristic city built inside a giant glass bottle floating in space",
config);
for (Part part : response.parts()) {
if (part.thought().orElse(false)) {
// Skip outputting thoughts
continue;
}
if (part.text().isPresent()) {
System.out.println(part.text().get());
} else if (part.inlineData().isPresent()) {
var blob = part.inlineData().get();
if (blob.data().isPresent()) {
Files.write(Paths.get("image.png"), blob.data().get());
System.out.println("Image saved as image.png");
}
}
}
}
}
}
using Google.GenAI;
using Google.GenAI.Types;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
public class ThinkingLevels {
public static async Task Main(string[] args) {
var client = new Client();
var response = await client.Models.GenerateContentAsync(
model: "gemini-nano-banana-2.1",
contents: "A futuristic city built inside a giant glass bottle floating in space",
config: new GenerateContentConfig
{
ResponseModalities = new List<string> { "IMAGE" },
ThinkingConfig = new ThinkingConfig
{
ThinkingLevel = ThinkingLevel.High,
IncludeThoughts = true
}
}
);
foreach (var candidate in response.Candidates) {
foreach (var part in candidate.Content.Parts) {
if (part.Thought == true) {
// Skip outputting thoughts
continue;
}
if (part.Text != null) {
Console.WriteLine(part.Text);
} else if (part.InlineData?.Data != null) {
await File.WriteAllBytesAsync("image.png", part.InlineData.Data);
Console.WriteLine("Image saved as image.png");
}
}
}
}
}
curl -s -X POST \
"https://generativelanguage.googleapis.com/v1/models/gemini-nano-banana-2.1:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"contents": [{"parts": [{"text": "A futuristic city built inside a giant glass bottle floating in space"}]}],
"generationConfig": {
"responseModalities": ["IMAGE"],
"thinkingConfig": {
"thinkingLevel": "HIGH",
"includeThoughts": true
}
}
}'
请注意,无论是否考虑 token 都会计费 includeThoughts 设置为 true 或 false,作为 思考过程 无论您是否查看进程,默认情况下都会发生。
思想签名 #
思想签名是模型内部思维过程的加密表示,用于在多轮交互中保留推理上下文。所有回复均包含 thought_signature 场。作为一般规则,如果您在模型响应中收到思想签名,则应在下一轮发送对话历史记录时完全按照收到的情况将其传回。未能传播思想签名可能会导致响应失败。检查 思想签名 有关签名整体更多解释的文档。
以下是思想签名的工作原理:
全部
inline_data有图像的零件mime_type作为响应的一部分应该有签名。如果想法后面的开头(任何图像之前)有一些文本部分,则第一个文本部分也应该有签名。
如果
inline_data有图像的零件mime_type是思想的一部分,它们不会有签名。
以下代码显示了包含思想签名的示例:
[
{
"inlineData": {
"data": "<base64_image_data_0>",
"mimeType": "image/png"
},
"thought": true // Thoughts don't have signatures
},
{
"inlineData": {
"data": "<base64_image_data_1>",
"mimeType": "image/png"
},
"thought": true // Thoughts don't have signatures
},
{
"inlineData": {
"data": "<base64_image_data_2>",
"mimeType": "image/png"
},
"thought": true // Thoughts don't have signatures
},
{
"text": "Here is a step-by-step guide to baking macarons, presented in three separate images.\n\n### Step 1: Piping the Batter\n\nThe first step after making your macaron batter is to pipe it onto a baking sheet. This requires a steady hand to create uniform circles.\n\n",
"thoughtSignature": "<Signature_A>" // The first non-thought part always has a signature
},
{
"inlineData": {
"data": "<base64_image_data_3>",
"mimeType": "image/png"
},
"thoughtSignature": "<Signature_B>" // All image parts have a signature
},
{
"text": "\n\n### Step 2: Baking and Developing Feet\n\nOnce piped, the macarons are baked in the oven. A key sign of a successful bake is the development of \"feet\" - the ruffled edge at the base of each macaron shell.\n\n"
// Follow-up text parts don't have signatures
},
{
"inlineData": {
"data": "<base64_image_data_4>",
"mimeType": "image/png"
},
"thoughtSignature": "<Signature_C>" // All image parts have a signature
},
{
"text": "\n\n### Step 3: Assembling the Macaron\n\nThe final step is to pair the cooled macaron shells by size and sandwich them together with your desired filling, creating the classic macaron dessert.\n\n"
},
{
"inlineData": {
"data": "<base64_image_data_5>",
"mimeType": "image/png"
},
"thoughtSignature": "<Signature_D>" // All image parts have a signature
}
]
其他图像生成模式 #
Gemini支持其他基于提示结构和上下文的图像交互模式,包括:
文本到图像和文本(交错): 输出带有相关文本的图像。 * 示例提示:“生成海鲜饭的图解食谱。”
图像和文本到图像和文本(交错):使用输入图像和文本创建新的相关图像和文本。 * 示例提示:(带有带家具的房间的图像)“我的空间还适合什么其他颜色的沙发?您可以更新图像吗?”
批量生成图像 #
如果需要生成大量图像,可以使用 Batch API。你变得更高 速率限制 换取最多 24 小时的周转时间。
检查 Batch API图像生成文档 和 食谱 Batch API 图像示例和代码。
提示指南和策略 #
掌握图像生成从一个基本原则开始:
描述场景,不要只列出关键词。 该模型的核心优势在于其深刻的语言理解。一个叙述性的、描述性的段落几乎总是会比一系列不连贯的单词产生更好、更连贯的图像。
生成图像的提示 #
以下策略将帮助您创建有效的提示来准确生成您正在寻找的图像。
摄影 #
对于逼真的图像,请使用摄影术语。提及相机角度、镜头类型、灯光和细节,以指导模型获得真实的结果。
提示 | 生成的输出 |
|---|---|
照片中是一位年长的日本陶艺家的特写肖像,他的皱纹深深地被阳光侵蚀,脸上挂着温暖而会心的微笑。他正在仔细检查一个刚刚上釉的茶碗。场景是他质朴、阳光普照的工作室。透过窗户的柔和的金色小时光照亮了场景,突出了粘土的细腻纹理。使用 85 毫米人像镜头拍摄,产生柔和、模糊的背景(散景)。整体气氛平静而高雅。垂直纵向方向。 |
|
风格化的插图和贴纸 #
要创建贴纸、图标或资源,请明确风格并要求白色背景。
提示 | 生成的输出 |
|---|---|
卡哇伊风格的贴纸,上面是一只戴着小竹帽的快乐小熊猫。它正在咀嚼一片绿色的竹叶。该设计具有大胆、简洁的轮廓、简单的卡通着色和充满活力的调色板。背景必须是白色的。 |
|
图像中的准确文字 #
Gemini 擅长渲染文本。清楚文本、字体样式(描述性)和整体设计。使用Gemini 3 Pro Image进行专业资产制作。
提示 | 生成的输出 |
|---|---|
为一家名为“The Daily Grind”的咖啡店创建一个现代、简约的标志。文本应采用干净、粗体、无衬线字体。配色方案是黑色和白色。将徽标放在一个圆圈中。巧妙地使用咖啡豆。 |
|
产品模型和商业摄影 #
非常适合为电子商务、广告或品牌创建干净、专业的产品照片。
提示 | 生成的输出 |
|---|---|
高分辨率、工作室照明的产品照片,展示了一个哑光黑色的简约陶瓷咖啡杯,呈现在抛光的混凝土表面上。照明采用三点柔光箱设置,旨在创造柔和的漫射高光并消除刺眼的阴影。相机角度稍微抬高45度拍摄,以展示其简洁的线条。超现实,重点关注从咖啡中升起的蒸汽。方形图像。 |
|
极简主义和负空间设计 #
非常适合为网站、演示文稿或营销材料创建背景,其中文本将被覆盖。
提示 | 生成的输出 |
|---|---|
极简主义构图,画面右下角有一片精致的红色枫叶。背景是一块巨大的、空白的灰白色画布,为文本创造了显着的负空间。来自左上角的柔和漫射照明。方形图像。 |
|
连续艺术(漫画面板/故事板) #
基于角色一致性和场景描述来创建用于视觉叙事的面板。为了保证文本的准确性和讲故事的能力,这些提示最适合与 Gemini 3.1 Pro 和 Gemini 3.1 Flash Image 配合使用。
提示 | 生成的输出 |
|---|---|
输入图像: |
|
使用 Google 搜索提供事实依据 #
使用 Google 搜索根据最近或实时信息生成图像。这对于新闻、天气和其他时间敏感的主题非常有用。
提示 | 生成的输出 |
|---|---|
制作昨晚阿森纳欧冠比赛的简单但时尚的图形 |
|
编辑图像的提示 #
这些示例展示了如何在文本提示旁边提供图像以进行编辑、合成和风格转换。
添加和删除元素 #
提供图像并描述您的更改。该模型将与原始图像的风格、灯光和视角相匹配。
提示 | 生成的输出 |
|---|---|
输入图像: |
|
修复(语义掩蔽) #
以对话方式定义“蒙版”来编辑图像的特定部分,同时保持其余部分不变。
提示 | 生成的输出 |
|---|---|
输入图像: |
|
风格转移 #
提供图像并要求模型以不同的艺术风格重新创建其内容。
提示 | 生成的输出 |
|---|---|
输入图像: |
|
高级合成:组合多个图像 #
提供多个图像作为上下文来创建新的复合场景。这非常适合产品模型或创意拼贴。
提示 | 生成的输出 |
|---|---|
输入图像: |
|
高保真细节保留 #
为了确保在编辑过程中保留关键细节(例如面孔或徽标),请在编辑请求中详细描述它们。
提示 | 生成的输出 |
|---|---|
输入图像: |
|
赋予生活一些东西 #
上传粗略的草图或绘图,并要求模特将其细化为成品图像。
提示 | 生成的输出 |
|---|---|
输入图像: |
|
字符一致性:360 查看 #
您可以通过迭代提示不同角度来生成角色的 360 度视图。为了获得最佳结果,请在后续提示中包含先前生成的图像以保持一致性。对于复杂的姿势,请包含所需姿势的参考图像。
提示 | 生成的输出 |
|---|---|
输入图像: |
|
最佳实践 #
为了将您的结果从优秀提升到卓越,请将这些专业策略纳入您的工作流程中。
高度具体: 您提供的细节越多,您的控制权就越大。与其描述它是“幻想盔甲”,不如说:“华丽的精灵板甲,蚀刻有银叶图案,有高领和形状像猎鹰翅膀的肩甲。”
提供上下文和意图: 解释一下 目的 的图像。模型对上下文的理解将影响最终的输出。例如,“为高端、简约的护肤品牌创建徽标”会比仅仅“创建徽标”产生更好的结果。
迭代和细化: 不要指望第一次尝试就能获得完美的图像。利用模型的对话性质进行小的更改。跟进诸如“那太好了,但是你能让灯光暖一点吗?”之类的提示。或“保持一切不变,但将角色的表情改变得更严肃。”
使用分步说明: 对于包含许多元素的复杂场景,请将提示分成步骤。 “首先,创建一个黎明时分宁静、雾气弥漫的森林的背景。然后,在前景中添加一个长满青苔的古老石祭坛。最后,在祭坛顶部放置一把发光的剑。”
使用“语义否定提示”: 不要说“没有汽车”,而是积极地描述所需的场景:“一条空荡荡的、荒芜的街道,没有交通迹象。”
控制相机: 使用摄影和电影语言来控制构图。类似的术语
wide-angle shot,macro shot,low-angle perspective.
限制 #
为了获得最佳性能,请使用以下语言: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。
图像生成不支持音频输入。仅 Gemini Nano Banana 2.1、Gemini 3.1 Flash Image 和 Gemini 3.1 Flash Lite Image 支持视频输入。
该模型并不总是遵循用户明确要求的图像输出的确切数量。
gemini-2.5-flash-image最多可使用 3 图像作为输入,效果最佳,同时gemini-3-pro-image支持高保真5图像,最多支持14图像。gemini-nano-banana-2.1和gemini-3.1-flash-image在单个工作流程中支持最多 4 字符的字符相似度和最多 10 对象的保真度。为图像生成文本时,如果您首先生成文本,然后请求带有文本的图像,则 Gemini 效果最佳。
gemini-nano-banana-2.1和gemini-3.1-flash-image事实依据和 Google 搜索目前不支持使用来自网络搜索的真实世界人物图像。所有生成的图像都包含 SynthID水印.
可选配置 #
您可以选择在中配置模型输出的响应模式和纵横比 config 的领域 generate_content 来电。
输出类型 #
该模型默认返回文本和图像响应(即 response_modalities=['Text', 'Image'])。您可以使用以下命令将响应配置为仅返回图像而不返回文本 response_modalities=['Image'].
response = client.models.generate_content(
model="gemini-nano-banana-2.1",
contents=[prompt],
config=types.GenerateContentConfig(
response_modalities=['Image']
)
)
const response = await ai.models.generateContent({
model: "gemini-nano-banana-2.1",
contents: prompt,
config: {
responseModalities: ['Image']
}
});
result, _ := client.Models.GenerateContent(
ctx,
"gemini-nano-banana-2.1",
genai.Text("Create a picture of a nano banana dish in a " +
" fancy restaurant with a Gemini theme"),
&genai.GenerateContentConfig{
ResponseModalities: []string{"IMAGE"},
},
)
response = client.models.generateContent(
"gemini-nano-banana-2.1",
prompt,
GenerateContentConfig.builder()
.responseModalities("IMAGE")
.build());
var response = await client.Models.GenerateContentAsync(
model: "gemini-nano-banana-2.1",
contents: prompt,
config: new GenerateContentConfig
{
ResponseModalities = new List<string> { "IMAGE" }
}
);
curl -s -X POST \
"https://generativelanguage.googleapis.com/v1/models/gemini-nano-banana-2.1:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"contents": [{
"parts": [
{"text": "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme"}
]
}],
"generationConfig": {
"responseModalities": ["Image"]
}
}'
宽高比和图像尺寸 #
该模型默认将输出图像大小与输入图像大小相匹配,或者以其他方式生成 1:1 正方形。您可以使用以下命令控制输出图像的纵横比 aspect_ratio 下的字段 image_config 在响应请求中,如下所示:
# For gemini-2.5-flash-image
response = client.models.generate_content(
model="gemini-2.5-flash-image",
contents=[prompt],
config=types.GenerateContentConfig(
image_config=types.ImageConfig(
aspect_ratio="16:9",
)
)
)
# For gemini-nano-banana-2.1, gemini-3.1-flash-image, and gemini-3-pro-image
response = client.models.generate_content(
model="gemini-nano-banana-2.1",
contents=[prompt],
config=types.GenerateContentConfig(
image_config=types.ImageConfig(
aspect_ratio="16:9",
image_size="2K",
)
)
)
// For gemini-2.5-flash-image
const response = await ai.models.generateContent({
model: "gemini-2.5-flash-image",
contents: prompt,
config: {
imageConfig: {
aspectRatio: "16:9",
},
}
});
// For gemini-nano-banana-2.1, gemini-3.1-flash-image, and gemini-3-pro-image
const response_gemini3 = await ai.models.generateContent({
model: "gemini-nano-banana-2.1",
contents: prompt,
config: {
imageConfig: {
aspectRatio: "16:9",
imageSize: "2K",
},
}
});
// For gemini-2.5-flash-image
result, _ := client.Models.GenerateContent(
ctx,
"gemini-2.5-flash-image",
genai.Text("Create a picture of a nano banana dish in a " +
" fancy restaurant with a Gemini theme"),
&genai.GenerateContentConfig{
ImageConfig: &genai.ImageConfig{
AspectRatio: "16:9",
},
},
)
// For gemini-nano-banana-2.1, gemini-3.1-flash-image, and gemini-3-pro-image
result_gemini3, _ := client.Models.GenerateContent(
ctx,
"gemini-nano-banana-2.1",
genai.Text("Create a picture of a nano banana dish in a " +
" fancy restaurant with a Gemini theme"),
&genai.GenerateContentConfig{
ImageConfig: &genai.ImageConfig{
AspectRatio: "16:9",
ImageSize: "2K",
},
},
)
// For gemini-2.5-flash-image
response = client.models.generateContent(
"gemini-2.5-flash-image",
prompt,
GenerateContentConfig.builder()
.imageConfig(ImageConfig.builder()
.aspectRatio("16:9")
.build())
.build());
// For gemini-nano-banana-2.1, gemini-3.1-flash-image, and gemini-3-pro-image
response_gemini3 = client.models.generateContent(
"gemini-nano-banana-2.1",
prompt,
GenerateContentConfig.builder()
.imageConfig(ImageConfig.builder()
.aspectRatio("16:9")
.imageSize("2K")
.build())
.build());
// For gemini-2.5-flash-image
var response = await client.Models.GenerateContentAsync(
model: "gemini-2.5-flash-image",
contents: prompt,
config: new GenerateContentConfig
{
ImageConfig = new ImageConfig
{
AspectRatio = "16:9"
}
}
);
// For gemini-nano-banana-2.1, gemini-3.1-flash-image, and gemini-3-pro-image
var response_gemini3 = await client.Models.GenerateContentAsync(
model: "gemini-nano-banana-2.1",
contents: prompt,
config: new GenerateContentConfig
{
ImageConfig = new ImageConfig
{
AspectRatio = "16:9",
ImageSize = "2K"
}
}
);
# For gemini-2.5-flash-image
curl -s -X POST \
"https://generativelanguage.googleapis.com/v1/models/gemini-2.5-flash-image:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"contents": [{
"parts": [
{"text": "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme"}
]
}],
"generationConfig": {
"imageConfig": {
"aspectRatio": "16:9"
}
}
}'
# For gemini-nano-banana-2.1, gemini-3.1-flash-image, and gemini-3-pro-image
curl -s -X POST \
"https://generativelanguage.googleapis.com/v1/models/gemini-nano-banana-2.1:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"contents": [{
"parts": [
{"text": "Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme"}
]
}],
"generationConfig": {
"imageConfig": {
"aspectRatio": "16:9",
"imageSize": "2K"
}
}
}'
下表列出了可用的不同比例和生成的图像的大小:
纵横比 | 1K分辨率 | 1K token | 2K分辨率 | 2K token | 4K分辨率 | 4K token |
|---|---|---|---|---|---|---|
1:1 | 1024x1024 | 1120 | 2048x2048 | 1680 | 4096x4096 | 2520 |
1:4 | 512x2048 | 1120 | 1024x4096 | 1680 | 2048x8192 | 2520 |
1:8 | 384x3072 | 1120 | 768x6144 | 1680 | 1536x12288 | 2520 |
2:3 | 848x1264 | 1120 | 1696x2528 | 1680 | 3392x5056 | 2520 |
3:2 | 1264x848 | 1120 | 2528x1696 | 1680 | 5056x3392 | 2520 |
3:4 | 896x1200 | 1120 | 1792x2400 | 1680 | 3584x4800 | 2520 |
4:1 | 2048x512 | 1120 | 4096x1024 | 1680 | 8192x2048 | 2520 |
4:3 | 1200x896 | 1120 | 2400x1792 | 1680 | 4800x3584 | 2520 |
4:5 | 928x1152 | 1120 | 1856x2304 | 1680 | 3712x4608 | 2520 |
5:4 | 1152x928 | 1120 | 2304x1856 | 1680 | 4608x3712 | 2520 |
8:1 | 3072x384 | 1120 | 6144x768 | 1680 | 12288x1536 | 2520 |
9:16 | 768x1376 | 1120 | 1536x2752 | 1680 | 3072x5504 | 2520 |
16:9 | 1376x768 | 1120 | 2752x1536 | 1680 | 5504x3072 | 2520 |
21:9 | 1584x672 | 1120 | 3168x1344 | 1680 | 6336x2688 | 2520 |
纵横比 | 512分辨率 | 0.5K token | 1K分辨率 | 1K token | 2K分辨率 | 2K token | 4K分辨率 | 4K token |
|---|---|---|---|---|---|---|---|---|
1:1 | 512x512 | 747 | 1024x1024 | 1120 | 2048x2048 | 1680 | 4096x4096 | 2520 |
1:4 | 256x1024 | 747 | 512x2048 | 1120 | 1024x4096 | 1680 | 2048x8192 | 2520 |
1:8 | 192x1536 | 747 | 384x3072 | 1120 | 768x6144 | 1680 | 1536x12288 | 2520 |
2:3 | 424x632 | 747 | 848x1264 | 1120 | 1696x2528 | 1680 | 3392x5056 | 2520 |
3:2 | 632x424 | 747 | 1264x848 | 1120 | 2528x1696 | 1680 | 5056x3392 | 2520 |
3:4 | 448x600 | 747 | 896x1200 | 1120 | 1792x2400 | 1680 | 3584x4800 | 2520 |
4:1 | 1024x256 | 747 | 2048x512 | 1120 | 4096x1024 | 1680 | 8192x2048 | 2520 |
4:3 | 600x448 | 747 | 1200x896 | 1120 | 2400x1792 | 1680 | 4800x3584 | 2520 |
4:5 | 464x576 | 747 | 928x1152 | 1120 | 1856x2304 | 1680 | 3712x4608 | 2520 |
5:4 | 576x464 | 747 | 1152x928 | 1120 | 2304x1856 | 1680 | 4608x3712 | 2520 |
8:1 | 1536x192 | 747 | 3072x384 | 1120 | 6144x768 | 1680 | 12288x1536 | 2520 |
9:16 | 384x688 | 747 | 768x1376 | 1120 | 1536x2752 | 1680 | 3072x5504 | 2520 |
16:9 | 688x384 | 747 | 1376x768 | 1120 | 2752x1536 | 1680 | 5504x3072 | 2520 |
21:9 | 792x168 | 747 | 1584x672 | 1120 | 3168x1344 | 1680 | 6336x2688 | 2520 |
纵横比 | 1K分辨率 | 1K token | 2K分辨率 | 2K token | 4K分辨率 | 4K token |
|---|---|---|---|---|---|---|
1:1 | 1024x1024 | 1120 | 2048x2048 | 1120 | 4096x4096 | 2000 |
2:3 | 848x1264 | 1120 | 1696x2528 | 1120 | 3392x5056 | 2000 |
3:2 | 1264x848 | 1120 | 2528x1696 | 1120 | 5056x3392 | 2000 |
3:4 | 896x1200 | 1120 | 1792x2400 | 1120 | 3584x4800 | 2000 |
4:3 | 1200x896 | 1120 | 2400x1792 | 1120 | 4800x3584 | 2000 |
4:5 | 928x1152 | 1120 | 1856x2304 | 1120 | 3712x4608 | 2000 |
5:4 | 1152x928 | 1120 | 2304x1856 | 1120 | 4608x3712 | 2000 |
9:16 | 768x1376 | 1120 | 1536x2752 | 1120 | 3072x5504 | 2000 |
16:9 | 1376x768 | 1120 | 2752x1536 | 1120 | 5504x3072 | 2000 |
21:9 | 1584x672 | 1120 | 3168x1344 | 1120 | 6336x2688 | 2000 |
纵横比 | 分辨率 | token |
|---|---|---|
1:1 | 1024x1024 | 1290 |
2:3 | 832x1248 | 1290 |
3:2 | 1248x832 | 1290 |
3:4 | 864x1184 | 1290 |
4:3 | 1184x864 | 1290 |
4:5 | 896x1152 | 1290 |
5:4 | 1152x896 | 1290 |
9:16 | 768x1344 | 1290 |
16:9 | 1344x768 | 1290 |
21:9 | 1536x672 | 1290 |
输入图像 提示: 使用高对比度黑白墨水以坚韧的黑色艺术风格制作 3 面板漫画。将人物置于幽默的场景中。
输入图像 提示: 请使用提供的我的猫的图像,在它的头上添加一顶小针织巫师帽。让它看起来坐得很舒服,并与照片的柔和灯光相匹配。
输入图像 提示: 使用提供的客厅图像,仅将蓝色沙发更改为复古棕色皮革切斯特菲尔德沙发。房间的其他部分保持不变,包括沙发上的枕头和灯光。
输入图像 提示: 将提供的现代城市街道夜间照片转换为文森特·梵高“星夜”的艺术风格。保留建筑物和汽车的原始构图,但用旋转的厚涂笔触以及深蓝色和亮黄色的戏剧性调色板渲染所有元素。
输入 1:连衣裙
输入 2:型号 提示: 打造专业的电商时尚写真。取出第一张图片中的蓝色碎花连衣裙,让第二张图片中的女士穿上它。生成穿着裙子的女性的逼真全身镜头,并调整灯光和阴影以匹配室外环境。
输入 1:女人
输入2:标志 提示: 拍摄第一张棕色头发、蓝色眼睛、表情中性的女人的照片。将第二张图片中的徽标添加到她的黑色 T 恤上。确保女性的脸部和特征保持完全不变。徽标应该看起来像自然地印在织物上,沿着衬衫的褶皱。
汽车的粗略草图 提示: 将这张未来汽车的粗略铅笔草图变成陈列室中成品概念车的精美照片。保持草图的流畅线条和低调,但添加金属蓝色油漆和霓虹灯边缘照明。
戴白眼镜的男人向右看
戴白眼镜的男人期待着