Bạn có thể yêu cầu mô hình Gemini Nano Banana tạo và chỉnh sửa hình ảnh bằng cả câu lệnh chỉ có văn bản và câu lệnh có cả văn bản và tệp. Khi sử dụng Firebase AI Logic, bạn có thể đưa ra yêu cầu này ngay trong ứng dụng của mình.
Với tính năng này, bạn có thể làm những việc như:
Tạo hình ảnh tạo sinh lặp lại thông qua cuộc trò chuyện bằng ngôn ngữ tự nhiên, điều chỉnh hình ảnh trong khi vẫn duy trì tính nhất quán và bối cảnh.
Tạo hình ảnh có khả năng hiển thị văn bản chất lượng cao, bao gồm cả các chuỗi văn bản dài.
Tạo kết quả dạng văn bản và hình ảnh xen kẽ. Ví dụ: một bài đăng trên blog có văn bản và hình ảnh trong một lượt. Trước đây, việc này đòi hỏi phải kết hợp nhiều mô hình.
Tạo hình ảnh bằng kiến thức về thế giới và khả năng suy luận của Gemini.
Bạn có thể định cấu hình phương thức phản hồi cho yêu cầu của mình để mô hình chỉ tạo hình ảnh hoặc cả hình ảnh và văn bản. Bạn có thể xem danh sách đầy đủ các tính năng được hỗ trợ (cùng với các câu lệnh mẫu) ở phần sau của trang này.
Chuyển đến mã cho tính năng chuyển văn bản thành hình ảnh Chuyển đến mã cho tính năng chuyển video thành hình ảnh Chuyển đến mã cho văn bản và hình ảnh xen kẽ
Chuyển đến mã để chỉnh sửa hình ảnh Chuyển đến mã để chỉnh sửa hình ảnh lặp lại
|
Xem các hướng dẫn khác để biết thêm các lựa chọn làm việc với hình ảnh Phân tích hình ảnh Phân tích hình ảnh trên thiết bị Tạo kết quả có cấu trúc |
Trước khi bắt đầu
|
Nhấp vào nhà cung cấp Gemini API của bạn để xem nội dung và mã dành riêng cho nhà cung cấp trên trang này. |
Nếu bạn chưa thực hiện, hãy hoàn tất
hướng dẫn bắt đầu sử dụng, trong đó mô tả cách
thiết lập dự án Firebase, kết nối ứng dụng với Firebase, thêm SDK,
khởi chạy dịch vụ phụ trợ cho nhà cung cấp Gemini API mà bạn chọn và
tạo một thực thể GenerativeModel.
Để thử nghiệm và lặp lại câu lệnh, bạn nên sử dụng Google AI Studio.
Các mô hình hỗ trợ tính năng này
gemini-nano-banana-2.1(Nano Banana 2.1)gemini-3.1-flash-image(Nano Banana 2)gemini-3.1-flash-lite-image(Nano Banana 2 Lite)gemini-3-pro-image(Nano Banana Pro)
Mô hình gemini-2.5-flash-image hỗ trợ chức năng này, nhưng không còn được dùng nữa.
Tạo và chỉnh sửa hình ảnh
Bạn có thể tạo và chỉnh sửa hình ảnh bằng mô hình Gemini Nano Banana.
Tạo hình ảnh (chỉ nhập văn bản)
|
Trước khi thử mẫu này, hãy hoàn tất phần Trước khi bắt đầu của hướng dẫn này để thiết lập dự án và ứng dụng của bạn. Trong phần đó, bạn cũng sẽ nhấp vào một nút cho nhà cung cấp Gemini API mà bạn đã chọn để xem nội dung dành riêng cho nhà cung cấp trên trang này. |
Bạn có thể yêu cầu mô hình Gemini Nano Banana tạo hình ảnh tạo sinh bằng cách đặt câu lệnh bằng văn bản.
Tạo một thực thể GenerativeModel,
thêm phương thức phản hồi của IMAGE vào cấu hình mô hình,
rồi gọi generateContent.
Swift
import FirebaseAILogic
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
let model = FirebaseAI.firebaseAI(backend: .googleAI()).generativeModel(
modelName: "gemini-nano-banana-2.1",
// Configure the model to respond with images only.
generationConfig: GenerationConfig(responseModalities: [.image])
)
// Provide a text prompt instructing the model to generate an image
let prompt = "Generate an image of the Eiffel tower with fireworks in the background."
// To generate an image, call `generateContent` with the text input
let response = try await model.generateContent(prompt)
// Handle the generated image
guard let inlineDataPart = response.inlineDataParts.first else {
fatalError("No image data in response.")
}
guard let uiImage = UIImage(data: inlineDataPart.data) else {
fatalError("Failed to convert data to UIImage.")
}
Kotlin
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel(
modelName = "gemini-nano-banana-2.1",
// Configure the model to respond with images only.
generationConfig = generationConfig {
responseModalities = listOf(ResponseModality.IMAGE) }
)
// Provide a text prompt instructing the model to generate an image
val prompt = "Generate an image of the Eiffel tower with fireworks in the background."
// To generate image output, call `generateContent` with the text input
val generatedImageAsBitmap = model.generateContent(prompt)
// Handle the generated image
.candidates.first().content.parts.filterIsInstance<ImagePart>().firstOrNull()?.image
Java
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI()).generativeModel(
"gemini-nano-banana-2.1",
// Configure the model to respond with images only.
new GenerationConfig.Builder()
.setResponseModalities(Arrays.asList(ResponseModality.IMAGE))
.build()
);
GenerativeModelFutures model = GenerativeModelFutures.from(ai);
// Provide a text prompt instructing the model to generate an image
Content prompt = new Content.Builder()
.addText("Generate an image of the Eiffel Tower with fireworks in the background.")
.build();
// To generate an image, call `generateContent` with the text input
ListenableFuture<GenerateContentResponse> response = model.generateContent(prompt);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
@Override
public void onSuccess(GenerateContentResponse result) {
// iterate over all the parts in the first candidate in the result object
for (Part part : result.getCandidates().get(0).getContent().getParts()) {
if (part instanceof ImagePart) {
ImagePart imagePart = (ImagePart) part;
// The returned image as a bitmap
Bitmap generatedImageAsBitmap = imagePart.getImage();
break;
}
}
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
}, executor);
Web
import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend, ResponseModality } from "firebase/ai";
// TODO(developer): Replace the following with your app's Firebase configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
// ...
};
// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);
// Initialize the Gemini Developer API backend service.
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });
// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(ai, {
model: "gemini-nano-banana-2.1",
// Configure the model to respond with images only.
generationConfig: {
responseModalities: [ResponseModality.IMAGE],
},
});
// Provide a text prompt instructing the model to generate an image
const prompt = 'Generate an image of the Eiffel Tower with fireworks in the background.';
// To generate an image, call `generateContent` with the text input
const result = model.generateContent(prompt);
// Handle the generated image
try {
const inlineDataParts = result.response.inlineDataParts();
if (inlineDataParts?.[0]) {
const image = inlineDataParts[0].inlineData;
console.log(image.mimeType, image.data);
}
} catch (err) {
console.error('Prompt or candidate was blocked:', err);
}
Dart
import 'package:firebase_ai/firebase_ai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
final model = FirebaseAI.googleAI().generativeModel(
model: 'gemini-nano-banana-2.1',
// Configure the model to respond with images only.
generationConfig: GenerationConfig(responseModalities: [ResponseModalities.image]),
);
// Provide a text prompt instructing the model to generate an image
final prompt = [Content.text('Generate an image of the Eiffel Tower with fireworks in the background.')];
// To generate an image, call `generateContent` with the text input
final response = await model.generateContent(prompt);
if (response.inlineDataParts.isNotEmpty) {
final imageBytes = response.inlineDataParts[0].bytes;
// Process the image
} else {
// Handle the case where no images were generated
print('Error: No images were generated.');
}
Unity
using Firebase;
using Firebase.AI;
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
var model = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI()).GetGenerativeModel(
modelName: "gemini-nano-banana-2.1",
// Configure the model to respond with images only.
generationConfig: new GenerationConfig(
responseModalities: new[] { ResponseModality.Image })
);
// Provide a text prompt instructing the model to generate an image
var prompt = "Generate an image of the Eiffel Tower with fireworks in the background.";
// To generate an image, call `GenerateContentAsync` with the text input
var response = await model.GenerateContentAsync(prompt);
// Handle the generated image
var imageParts = response.Candidates.First().Content.Parts
.OfType<ModelContent.InlineDataPart>()
.Where(part => part.MimeType == "image/png");
foreach (var imagePart in imageParts) {
// Load the Image into a Unity Texture2D object
UnityEngine.Texture2D texture2D = new(2, 2);
if (texture2D.LoadImage(imagePart.Data.ToArray())) {
// Do something with the image
}
}
Chỉnh sửa hình ảnh (đầu vào dạng văn bản và hình ảnh)
|
Trước khi thử mẫu này, hãy hoàn tất phần Trước khi bắt đầu của hướng dẫn này để thiết lập dự án và ứng dụng của bạn. Trong phần đó, bạn cũng sẽ nhấp vào một nút cho nhà cung cấp Gemini API mà bạn đã chọn để xem nội dung dành riêng cho nhà cung cấp trên trang này. |
Bạn có thể yêu cầu mô hình Gemini Nano Banana chỉnh sửa hình ảnh bằng cách đưa ra câu lệnh bằng văn bản và một hoặc nhiều hình ảnh.
Tạo một thực thể GenerativeModel,
thêm phương thức phản hồi của IMAGE vào cấu hình mô hình,
rồi gọi generateContent.
Swift
import FirebaseAILogic
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
let model = FirebaseAI.firebaseAI(backend: .googleAI()).generativeModel(
modelName: "gemini-nano-banana-2.1",
// Configure the model to respond with images only.
generationConfig: GenerationConfig(responseModalities: [.image])
)
// Provide an image for the model to edit
guard let image = UIImage(named: "scones") else { fatalError("Image file not found.") }
// Provide a text prompt instructing the model to edit the image
let prompt = "Edit this image to make it look like a cartoon"
// To edit the image, call `generateContent` with the image and text input
let response = try await model.generateContent(image, prompt)
// Handle the generated image
guard let inlineDataPart = response.inlineDataParts.first else {
fatalError("No image data in response.")
}
guard let uiImage = UIImage(data: inlineDataPart.data) else {
fatalError("Failed to convert data to UIImage.")
}
Kotlin
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel(
modelName = "gemini-nano-banana-2.1",
// Configure the model to respond with images only.
generationConfig = generationConfig {
responseModalities = listOf(ResponseModality.IMAGE) }
)
// Provide an image for the model to edit
val bitmap = BitmapFactory.decodeResource(context.resources, R.drawable.scones)
// Provide a text prompt instructing the model to edit the image
val prompt = content {
image(bitmap)
text("Edit this image to make it look like a cartoon")
}
// To edit the image, call `generateContent` with the prompt (image and text input)
val generatedImageAsBitmap = model.generateContent(prompt)
// Handle the generated text and image
.candidates.first().content.parts.filterIsInstance<ImagePart>().firstOrNull()?.image
Java
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI()).generativeModel(
"gemini-nano-banana-2.1",
// Configure the model to respond with images only.
new GenerationConfig.Builder()
.setResponseModalities(Arrays.asList(ResponseModality.IMAGE))
.build()
);
GenerativeModelFutures model = GenerativeModelFutures.from(ai);
// Provide an image for the model to edit
Bitmap bitmap = BitmapFactory.decodeResource(resources, R.drawable.scones);
// Provide a text prompt instructing the model to edit the image
Content promptcontent = new Content.Builder()
.addImage(bitmap)
.addText("Edit this image to make it look like a cartoon")
.build();
// To edit the image, call `generateContent` with the prompt (image and text input)
ListenableFuture<GenerateContentResponse> response = model.generateContent(promptcontent);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
@Override
public void onSuccess(GenerateContentResponse result) {
// iterate over all the parts in the first candidate in the result object
for (Part part : result.getCandidates().get(0).getContent().getParts()) {
if (part instanceof ImagePart) {
ImagePart imagePart = (ImagePart) part;
Bitmap generatedImageAsBitmap = imagePart.getImage();
break;
}
}
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
}, executor);
Web
import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend, ResponseModality } from "firebase/ai";
// TODO(developer): Replace the following with your app's Firebase configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
// ...
};
// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);
// Initialize the Gemini Developer API backend service.
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });
// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(ai, {
model: "gemini-nano-banana-2.1",
// Configure the model to respond with images only.
generationConfig: {
responseModalities: [ResponseModality.IMAGE],
},
});
// Prepare an image for the model to edit
async function fileToGenerativePart(file) {
const base64EncodedDataPromise = new Promise((resolve) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result.split(',')[1]);
reader.readAsDataURL(file);
});
return {
type: "inlineData",
inlineData: { data: await base64EncodedDataPromise, mimeType: file.type },
};
}
// Provide a text prompt instructing the model to edit the image
const prompt = "Edit this image to make it look like a cartoon";
const fileInputEl = document.querySelector("input[type=file]");
const imagePart = await fileToGenerativePart(fileInputEl.files[0]);
// To edit the image, call `generateContent` with the image and text input
const result = await model.generateContent([prompt, imagePart]);
// Handle the generated image
try {
const inlineDataParts = result.response.inlineDataParts();
if (inlineDataParts?.[0]) {
const image = inlineDataParts[0].inlineData;
console.log(image.mimeType, image.data);
}
} catch (err) {
console.error('Prompt or candidate was blocked:', err);
}
Dart
import 'package:firebase_ai/firebase_ai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
final model = FirebaseAI.googleAI().generativeModel(
model: 'gemini-nano-banana-2.1',
// Configure the model to respond with images only.
generationConfig: GenerationConfig(responseModalities: [ResponseModalities.image]),
);
// Prepare an image for the model to edit
final image = await File('scones.jpg').readAsBytes();
final imagePart = InlineDataPart('image/jpeg', image);
// Provide a text prompt instructing the model to edit the image
final prompt = TextPart("Edit this image to make it look like a cartoon");
// To edit the image, call `generateContent` with the image and text input
final response = await model.generateContent([
Content.multi([prompt,imagePart])
]);
// Handle the generated image
if (response.inlineDataParts.isNotEmpty) {
final imageBytes = response.inlineDataParts[0].bytes;
// Process the image
} else {
// Handle the case where no images were generated
print('Error: No images were generated.');
}
Unity
using Firebase;
using Firebase.AI;
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
var model = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI()).GetGenerativeModel(
modelName: "gemini-nano-banana-2.1",
// Configure the model to respond with images only.
generationConfig: new GenerationConfig(
responseModalities: new[] { ResponseModality.Image })
);
// Prepare an image for the model to edit
var imageFile = System.IO.File.ReadAllBytes(System.IO.Path.Combine(
UnityEngine.Application.streamingAssetsPath, "scones.jpg"));
var image = ModelContent.InlineData("image/jpeg", imageFile);
// Provide a text prompt instructing the model to edit the image
var prompt = ModelContent.Text("Edit this image to make it look like a cartoon.");
// To edit the image, call `GenerateContent` with the image and text input
var response = await model.GenerateContentAsync(new [] { prompt, image });
// Handle the generated image
var imageParts = response.Candidates.First().Content.Parts
.OfType<ModelContent.InlineDataPart>()
.Where(part => part.MimeType == "image/png");
foreach (var imagePart in imageParts) {
// Load the Image into a Unity Texture2D object
Texture2D texture2D = new Texture2D(2, 2);
if (texture2D.LoadImage(imagePart.Data.ToArray())) {
// Do something with the image
}
}
Tạo hình ảnh từ video đầu vào (văn bản và video đầu vào)
|
Trước khi thử mẫu này, hãy hoàn tất phần Trước khi bắt đầu của hướng dẫn này để thiết lập dự án và ứng dụng của bạn. Trong phần đó, bạn cũng sẽ nhấp vào một nút cho nhà cung cấp Gemini API mà bạn đã chọn để xem nội dung dành riêng cho nhà cung cấp trên trang này. |
Bạn có thể yêu cầu mô hình Gemini Nano Banana tạo hình ảnh tạo sinh bằng cách đặt câu lệnh dạng văn bản và video.
Tạo một thực thể GenerativeModel,
thêm phương thức phản hồi của IMAGE vào cấu hình mô hình,
rồi gọi generateContent.
Swift
import FirebaseAILogic
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
let model = FirebaseAI.firebaseAI(backend: .googleAI()).generativeModel(
modelName: "gemini-nano-banana-2.1",
// Configure the model to respond with images only.
generationConfig: GenerationConfig(responseModalities: [.image])
)
// Provide the video as `Data` with the appropriate MIME type.
let video = InlineDataPart(data: try Data(contentsOf: videoURL), mimeType: "video/mp4")
// Provide a text prompt instructing the model to generate an image.
let prompt = "Generate a poster image that captures the key themes of this video."
// To generate an image, call `generateContent` with the video and text input.
let response = try await model.generateContent(video, prompt)
// Handle the generated image.
guard let inlineDataPart = response.inlineDataParts.first else {
fatalError("No image data in response.")
}
guard let uiImage = UIImage(data: inlineDataPart.data) else {
fatalError("Failed to convert data to UIImage.")
}
Kotlin
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel(
modelName = "gemini-nano-banana-2.1",
// Configure the model to respond with images only.
generationConfig = generationConfig {
responseModalities = listOf(ResponseModality.IMAGE) }
)
val contentResolver = applicationContext.contentResolver
contentResolver.openInputStream(videoUri).use { stream ->
stream?.let {
val bytes = stream.readBytes()
// Provide a prompt that includes the video specified above and text.
val prompt = content {
inlineData(bytes, "video/mp4")
text("Generate a poster image that captures the key themes of this video.")
}
// Call generateContent with the prompt (video and text input).
val response = model.generateContent(prompt)
// Handle the generated image.
val generatedImageAsBitmap = response.candidates.first().content.parts
.filterIsInstance<ImagePart>().firstOrNull()?.image
}
}
Java
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI()).generativeModel(
"gemini-nano-banana-2.1",
// Configure the model to respond with images only.
new GenerationConfig.Builder()
.setResponseModalities(Arrays.asList(ResponseModality.IMAGE))
.build()
);
GenerativeModelFutures model = GenerativeModelFutures.from(ai);
ContentResolver resolver = getApplicationContext().getContentResolver();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try (java.io.InputStream inputStream = resolver.openInputStream(videoUri)) {
if (inputStream != null) {
int bytesRead;
byte[] buffer = new byte[16384];
while ((bytesRead = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, bytesRead);
}
}
} catch (IOException e) {
e.printStackTrace();
}
// Provide a prompt that includes the video specified above and text.
Content promptContent = new Content.Builder()
.addInlineData(byteArrayOutputStream.toByteArray(), "video/mp4")
.addText("Generate a poster image that captures the key themes of this video.")
.build();
// Call generateContent with the prompt (video and text input).
ListenableFuture<GenerateContentResponse> response = model.generateContent(promptContent);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
@Override
public void onSuccess(GenerateContentResponse result) {
// We didn't get any images back from the model.
if (result.getCandidates().isEmpty()) {
return;
}
// Handle the generated image.
for (Part part : result.getCandidates().get(0).getContent().getParts()) {
if (part instanceof ImagePart) {
ImagePart imagePart = (ImagePart) part;
Bitmap generatedImageAsBitmap = imagePart.getImage();
break;
}
}
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
}, executor);
Web
import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend, ResponseModality } from "firebase/ai";
// TODO(developer): Replace the following with your app's Firebase configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
// ...
};
// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);
// Initialize the Gemini Developer API backend service.
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });
// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(ai, {
model: "gemini-nano-banana-2.1",
// Configure the model to respond with images only.
generationConfig: {
responseModalities: [ResponseModality.IMAGE],
},
});
// Converts a File object to a Part object.
async function fileToGenerativePart(file) {
const base64EncodedDataPromise = new Promise((resolve) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result.split(',')[1]);
reader.readAsDataURL(file);
});
return {
inlineData: { data: await base64EncodedDataPromise, mimeType: file.type },
};
}
async function run() {
// Provide a text prompt instructing the model to generate an image.
const prompt = "Generate a poster image that captures the key themes of this video.";
const fileInputEl = document.querySelector("input[type=file]");
const videoPart = await fileToGenerativePart(fileInputEl.files[0]);
// Call generateContent with the video and text input.
const result = await model.generateContent([prompt, videoPart]);
// Handle the generated image.
try {
const inlineDataParts = result.response.inlineDataParts();
if (inlineDataParts?.[0]) {
const image = inlineDataParts[0].inlineData;
console.log(image.mimeType, image.data);
}
} catch (err) {
console.error('Prompt or candidate was blocked:', err);
}
}
run();
Dart
import 'package:firebase_ai/firebase_ai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
final model = FirebaseAI.googleAI().generativeModel(
model: 'gemini-nano-banana-2.1',
// Configure the model to respond with images only.
generationConfig: GenerationConfig(responseModalities: [ResponseModalities.image]),
);
// Prepare video for input.
final video = await File('video0.mp4').readAsBytes();
final videoPart = InlineDataPart('video/mp4', video);
// Provide a text prompt instructing the model to generate an image.
final prompt = TextPart("Generate a poster image that captures the key themes of this video.");
// Call generateContent with the video and text input.
final response = await model.generateContent([
Content.multi([prompt, videoPart])
]);
// Handle the generated image.
if (response.inlineDataParts.isNotEmpty) {
final imageBytes = response.inlineDataParts.first.bytes;
// Process the image.
} else {
// Handle the case where no images were generated.
print('Error: No images were generated.');
}
Unity
using Firebase;
using Firebase.AI;
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
var model = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI()).GetGenerativeModel(
modelName: "gemini-nano-banana-2.1",
// Configure the model to respond with images only.
generationConfig: new GenerationConfig(
responseModalities: new[] { ResponseModality.Image })
);
// Prepare a video for input.
var videoFile = System.IO.File.ReadAllBytes(System.IO.Path.Combine(
UnityEngine.Application.streamingAssetsPath, "yourVideo.mp4"));
var video = ModelContent.InlineData("video/mp4", videoFile);
// Provide a text prompt instructing the model to generate an image.
var prompt = ModelContent.Text("Generate a poster image that captures the key themes of this video.");
// Call GenerateContentAsync with the video and text input.
var response = await model.GenerateContentAsync(new [] { prompt, video });
// Handle the generated image.
var imageParts = response.Candidates.First().Content.Parts
.OfType<ModelContent.InlineDataPart>()
.Where(part => part.MimeType == "image/png");
foreach (var imagePart in imageParts) {
// Load the Image into a Unity Texture2D object.
Texture2D texture2D = new Texture2D(2, 2);
if (texture2D.LoadImage(imagePart.Data.ToArray())) {
// Do something with the image.
}
}
Tạo hình ảnh và văn bản xen kẽ
|
Trước khi thử mẫu này, hãy hoàn tất phần Trước khi bắt đầu của hướng dẫn này để thiết lập dự án và ứng dụng của bạn. Trong phần đó, bạn cũng sẽ nhấp vào một nút cho nhà cung cấp Gemini API mà bạn đã chọn để xem nội dung dành riêng cho nhà cung cấp trên trang này. |
Bạn có thể yêu cầu một mô hình Gemini Nano Banana tạo hình ảnh xen kẽ với câu trả lời dạng văn bản. Ví dụ: bạn có thể tạo hình ảnh tạo sinh về từng bước của một công thức được tạo cùng với hướng dẫn của bước đó mà không cần gửi yêu cầu riêng cho mô hình hoặc các mô hình khác.
Tạo một thực thể GenerativeModel,
thêm các phương thức phản hồi của TEXT và IMAGE vào cấu hình mô hình,
rồi gọi generateContent.
Swift
import FirebaseAILogic
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
let model = FirebaseAI.firebaseAI(backend: .googleAI()).generativeModel(
modelName: "gemini-nano-banana-2.1",
// Configure the model to respond with text and images.
generationConfig: GenerationConfig(responseModalities: [.text, .image])
)
// Provide a text prompt instructing the model to generate interleaved text and images
let prompt = """
Generate an illustrated recipe for a paella.
Create images to go alongside the text as you generate the recipe
"""
// To generate interleaved text and images, call `generateContent` with the text input
let response = try await model.generateContent(prompt)
// Handle the generated text and image
guard let candidate = response.candidates.first else {
fatalError("No candidates in response.")
}
for part in candidate.content.parts {
switch part {
case let textPart as TextPart:
// Do something with the generated text
let text = textPart.text
case let inlineDataPart as InlineDataPart:
// Do something with the generated image
guard let uiImage = UIImage(data: inlineDataPart.data) else {
fatalError("Failed to convert data to UIImage.")
}
default:
fatalError("Unsupported part type: \(part)")
}
}
Kotlin
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel(
modelName = "gemini-nano-banana-2.1",
// Configure the model to respond with text and images.
generationConfig = generationConfig {
responseModalities = listOf(ResponseModality.TEXT, ResponseModality.IMAGE) }
)
// Provide a text prompt instructing the model to generate interleaved text and images
val prompt = """
Generate an illustrated recipe for a paella.
Create images to go alongside the text as you generate the recipe
""".trimIndent()
// To generate interleaved text and images, call `generateContent` with the text input
val responseContent = model.generateContent(prompt).candidates.first().content
// The response will contain image and text parts interleaved
for (part in responseContent.parts) {
when (part) {
is ImagePart -> {
// ImagePart as a bitmap
val generatedImageAsBitmap: Bitmap? = part.asImageOrNull()
}
is TextPart -> {
// Text content from the TextPart
val text = part.text
}
}
}
Java
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI()).generativeModel(
"gemini-nano-banana-2.1",
// Configure the model to respond with text and images.
new GenerationConfig.Builder()
.setResponseModalities(Arrays.asList(ResponseModality.TEXT, ResponseModality.IMAGE))
.build()
);
GenerativeModelFutures model = GenerativeModelFutures.from(ai);
// Provide a text prompt instructing the model to generate interleaved text and images
Content prompt = new Content.Builder()
.addText("Generate an illustrated recipe for a paella.\n" +
"Create images to go alongside the text as you generate the recipe")
.build();
// To generate interleaved text and images, call `generateContent` with the text input
ListenableFuture<GenerateContentResponse> response = model.generateContent(prompt);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
@Override
public void onSuccess(GenerateContentResponse result) {
Content responseContent = result.getCandidates().get(0).getContent();
// The response will contain image and text parts interleaved
for (Part part : responseContent.getParts()) {
if (part instanceof ImagePart) {
// ImagePart as a bitmap
Bitmap generatedImageAsBitmap = ((ImagePart) part).getImage();
} else if (part instanceof TextPart){
// Text content from the TextPart
String text = ((TextPart) part).getText();
}
}
}
@Override
public void onFailure(Throwable t) {
System.err.println(t);
}
}, executor);
Web
import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend, ResponseModality } from "firebase/ai";
// TODO(developer): Replace the following with your app's Firebase configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
// ...
};
// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);
// Initialize the Gemini Developer API backend service.
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });
// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(ai, {
model: "gemini-nano-banana-2.1",
// Configure the model to respond with text and images.
generationConfig: {
responseModalities: [ResponseModality.TEXT, ResponseModality.IMAGE],
},
});
// Provide a text prompt instructing the model to generate interleaved text and images
const prompt = 'Generate an illustrated recipe for a paella.\n.' +
'Create images to go alongside the text as you generate the recipe';
// To generate interleaved text and images, call `generateContent` with the text input
const result = await model.generateContent(prompt);
// Handle the generated text and image
try {
const response = result.response;
if (response.candidates?.[0].content?.parts) {
for (const part of response.candidates?.[0].content?.parts) {
if (part.type === "text") {
// Do something with the text
console.log(part.text);
}
if (part.type === "inlineData") {
// Do something with the image
const image = part.inlineData;
console.log(image.mimeType, image.data);
}
}
}
} catch (err) {
console.error('Prompt or candidate was blocked:', err);
}
Dart
import 'package:firebase_ai/firebase_ai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
final model = FirebaseAI.googleAI().generativeModel(
model: 'gemini-nano-banana-2.1',
// Configure the model to respond with text and images.
generationConfig: GenerationConfig(responseModalities: [ResponseModalities.text, ResponseModalities.image]),
);
// Provide a text prompt instructing the model to generate interleaved text and images
final prompt = [Content.text(
'Generate an illustrated recipe for a paella\n ' +
'Create images to go alongside the text as you generate the recipe'
)];
// To generate interleaved text and images, call `generateContent` with the text input
final response = await model.generateContent(prompt);
// Handle the generated text and image
final parts = response.candidates.firstOrNull?.content.parts;
if (parts != null && parts.isNotEmpty) {
for (final part in parts) {
if (part is TextPart) {
// Do something with text part
final text = part.text;
}
if (part is InlineDataPart) {
// Process image
final imageBytes = part.bytes;
}
}
} else {
// Handle the case where no images were generated
print('Error: No images were generated.');
}
Unity
using Firebase;
using Firebase.AI;
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
var model = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI()).GetGenerativeModel(
modelName: "gemini-nano-banana-2.1",
// Configure the model to respond with text and images.
generationConfig: new GenerationConfig(
responseModalities: new[] { ResponseModality.Text, ResponseModality.Image })
);
// Provide a text prompt instructing the model to generate interleaved text and images
var prompt = "Generate an illustrated recipe for a paella \n" +
"Create images to go alongside the text as you generate the recipe";
// To generate interleaved text and images, call `GenerateContentAsync` with the text input
var response = await model.GenerateContentAsync(prompt);
// Handle the generated text and image
foreach (var part in response.Candidates.First().Content.Parts) {
if (part is ModelContent.TextPart textPart) {
if (!string.IsNullOrWhiteSpace(textPart.Text)) {
// Do something with the text
}
} else if (part is ModelContent.InlineDataPart dataPart) {
if (dataPart.MimeType == "image/png") {
// Load the Image into a Unity Texture2D object
UnityEngine.Texture2D texture2D = new(2, 2);
if (texture2D.LoadImage(dataPart.Data.ToArray())) {
// Do something with the image
}
}
}
}
Tinh chỉnh và chỉnh sửa hình ảnh bằng tính năng trò chuyện nhiều lượt
|
Trước khi thử mẫu này, hãy hoàn tất phần Trước khi bắt đầu của hướng dẫn này để thiết lập dự án và ứng dụng của bạn. Trong phần đó, bạn cũng sẽ nhấp vào một nút cho nhà cung cấp Gemini API mà bạn đã chọn để xem nội dung dành riêng cho nhà cung cấp trên trang này. |
Bằng cách sử dụng tính năng trò chuyện nhiều lượt, bạn có thể lặp lại với mô hình Gemini Nano Banana trên hình ảnh mà mô hình đó tạo ra hoặc bạn cung cấp.
Tạo một thực thể GenerativeModel,
thêm phương thức phản hồi của IMAGE vào cấu hình mô hình,
rồi gọi startChat() và sendMessage() để gửi tin nhắn mới của người dùng.
Swift
import FirebaseAILogic
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
let model = FirebaseAI.firebaseAI(backend: .googleAI()).generativeModel(
modelName: "gemini-nano-banana-2.1",
// Configure the model to respond with images only.
generationConfig: GenerationConfig(responseModalities: [.image])
)
// Initialize the chat
let chat = model.startChat()
guard let image = UIImage(named: "scones") else { fatalError("Image file not found.") }
// Provide an initial text prompt instructing the model to edit the image
let prompt = "Edit this image to make it look like a cartoon"
// To generate an initial response, send a user message with the image and text prompt
let response = try await chat.sendMessage(image, prompt)
// Inspect the generated image
guard let inlineDataPart = response.inlineDataParts.first else {
fatalError("No image data in response.")
}
guard let uiImage = UIImage(data: inlineDataPart.data) else {
fatalError("Failed to convert data to UIImage.")
}
// Follow up requests do not need to specify the image again
let followUpResponse = try await chat.sendMessage("But make it old-school line drawing style")
// Inspect the edited image after the follow up request
guard let followUpInlineDataPart = followUpResponse.inlineDataParts.first else {
fatalError("No image data in response.")
}
guard let followUpUIImage = UIImage(data: followUpInlineDataPart.data) else {
fatalError("Failed to convert data to UIImage.")
}
Kotlin
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel(
modelName = "gemini-nano-banana-2.1",
// Configure the model to respond with images only.
generationConfig = generationConfig {
responseModalities = listOf(ResponseModality.IMAGE) }
)
// Provide an image for the model to edit
val bitmap = BitmapFactory.decodeResource(context.resources, R.drawable.scones)
// Create the initial prompt instructing the model to edit the image
val prompt = content {
image(bitmap)
text("Edit this image to make it look like a cartoon")
}
// Initialize the chat
val chat = model.startChat()
// To generate an initial response, send a user message with the image and text prompt
var response = chat.sendMessage(prompt)
// Inspect the returned image
var generatedImageAsBitmap = response
.candidates.first().content.parts.filterIsInstance<ImagePart>().firstOrNull()?.image
// Follow up requests do not need to specify the image again
response = chat.sendMessage("But make it old-school line drawing style")
generatedImageAsBitmap = response
.candidates.first().content.parts.filterIsInstance<ImagePart>().firstOrNull()?.image
Java
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI()).generativeModel(
"gemini-nano-banana-2.1",
// Configure the model to respond with images only.
new GenerationConfig.Builder()
.setResponseModalities(Arrays.asList(ResponseModality.IMAGE))
.build()
);
GenerativeModelFutures model = GenerativeModelFutures.from(ai);
// Provide an image for the model to edit
Bitmap bitmap = BitmapFactory.decodeResource(resources, R.drawable.scones);
// Initialize the chat
ChatFutures chat = model.startChat();
// Create the initial prompt instructing the model to edit the image
Content prompt = new Content.Builder()
.setRole("user")
.addImage(bitmap)
.addText("Edit this image to make it look like a cartoon")
.build();
// To generate an initial response, send a user message with the image and text prompt
ListenableFuture<GenerateContentResponse> response = chat.sendMessage(prompt);
// Extract the image from the initial response
ListenableFuture<@Nullable Bitmap> initialRequest = Futures.transform(response, result -> {
for (Part part : result.getCandidates().get(0).getContent().getParts()) {
if (part instanceof ImagePart) {
ImagePart imagePart = (ImagePart) part;
return imagePart.getImage();
}
}
return null;
}, executor);
// Follow up requests do not need to specify the image again
ListenableFuture<GenerateContentResponse> modelResponseFuture = Futures.transformAsync(
initialRequest,
generatedImage -> {
Content followUpPrompt = new Content.Builder()
.addText("But make it old-school line drawing style")
.build();
return chat.sendMessage(followUpPrompt);
},
executor);
// Add a final callback to check the reworked image
Futures.addCallback(modelResponseFuture, new FutureCallback<GenerateContentResponse>() {
@Override
public void onSuccess(GenerateContentResponse result) {
for (Part part : result.getCandidates().get(0).getContent().getParts()) {
if (part instanceof ImagePart) {
ImagePart imagePart = (ImagePart) part;
Bitmap generatedImageAsBitmap = imagePart.getImage();
break;
}
}
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
}, executor);
Web
import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend, ResponseModality } from "firebase/ai";
// TODO(developer): Replace the following with your app's Firebase configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
// ...
};
// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);
// Initialize the Gemini Developer API backend service.
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });
// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(ai, {
model: "gemini-nano-banana-2.1",
// Configure the model to respond with images only.
generationConfig: {
responseModalities: [ResponseModality.IMAGE],
},
});
// Prepare an image for the model to edit
async function fileToGenerativePart(file) {
const base64EncodedDataPromise = new Promise((resolve) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result.split(',')[1]);
reader.readAsDataURL(file);
});
return {
type: "inlineData",
inlineData: { data: await base64EncodedDataPromise, mimeType: file.type },
};
}
const fileInputEl = document.querySelector("input[type=file]");
const imagePart = await fileToGenerativePart(fileInputEl.files[0]);
// Provide an initial text prompt instructing the model to edit the image
const prompt = "Edit this image to make it look like a cartoon";
// Initialize the chat
const chat = model.startChat();
// To generate an initial response, send a user message with the image and text prompt
const result = await chat.sendMessage([prompt, imagePart]);
// Request and inspect the generated image
try {
const inlineDataParts = result.response.inlineDataParts();
if (inlineDataParts?.[0]) {
// Inspect the generated image
const image = inlineDataParts[0].inlineData;
console.log(image.mimeType, image.data);
}
} catch (err) {
console.error('Prompt or candidate was blocked:', err);
}
// Follow up requests do not need to specify the image again
const followUpResult = await chat.sendMessage("But make it old-school line drawing style");
// Request and inspect the returned image
try {
const followUpInlineDataParts = followUpResult.response.inlineDataParts();
if (followUpInlineDataParts?.[0]) {
// Inspect the generated image
const followUpImage = followUpInlineDataParts[0].inlineData;
console.log(followUpImage.mimeType, followUpImage.data);
}
} catch (err) {
console.error('Prompt or candidate was blocked:', err);
}
Dart
import 'package:firebase_ai/firebase_ai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
final model = FirebaseAI.googleAI().generativeModel(
model: 'gemini-nano-banana-2.1',
// Configure the model to respond with images only.
generationConfig: GenerationConfig(responseModalities: [ResponseModalities.image]),
);
// Prepare an image for the model to edit
final image = await File('scones.jpg').readAsBytes();
final imagePart = InlineDataPart('image/jpeg', image);
// Provide an initial text prompt instructing the model to edit the image
final prompt = TextPart("Edit this image to make it look like a cartoon");
// Initialize the chat
final chat = model.startChat();
// To generate an initial response, send a user message with the image and text prompt
final response = await chat.sendMessage([
Content.multi([prompt,imagePart])
]);
// Inspect the returned image
if (response.inlineDataParts.isNotEmpty) {
final imageBytes = response.inlineDataParts[0].bytes;
// Process the image
} else {
// Handle the case where no images were generated
print('Error: No images were generated.');
}
// Follow up requests do not need to specify the image again
final followUpResponse = await chat.sendMessage([
Content.text("But make it old-school line drawing style")
]);
// Inspect the returned image
if (followUpResponse.inlineDataParts.isNotEmpty) {
final followUpImageBytes = response.inlineDataParts[0].bytes;
// Process the image
} else {
// Handle the case where no images were generated
print('Error: No images were generated.');
}
Unity
using Firebase;
using Firebase.AI;
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
var model = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI()).GetGenerativeModel(
modelName: "gemini-nano-banana-2.1",
// Configure the model to respond with images only.
generationConfig: new GenerationConfig(
responseModalities: new[] { ResponseModality.Image })
);
// Prepare an image for the model to edit
var imageFile = System.IO.File.ReadAllBytes(System.IO.Path.Combine(
UnityEngine.Application.streamingAssetsPath, "scones.jpg"));
var image = ModelContent.InlineData("image/jpeg", imageFile);
// Provide an initial text prompt instructing the model to edit the image
var prompt = ModelContent.Text("Edit this image to make it look like a cartoon.");
// Initialize the chat
var chat = model.StartChat();
// To generate an initial response, send a user message with the image and text prompt
var response = await chat.SendMessageAsync(new [] { prompt, image });
// Inspect the returned image
var imageParts = response.Candidates.First().Content.Parts
.OfType<ModelContent.InlineDataPart>()
.Where(part => part.MimeType == "image/png");
// Load the image into a Unity Texture2D object
UnityEngine.Texture2D texture2D = new(2, 2);
if (texture2D.LoadImage(imageParts.First().Data.ToArray())) {
// Do something with the image
}
// Follow up requests do not need to specify the image again
var followUpResponse = await chat.SendMessageAsync("But make it old-school line drawing style");
// Inspect the returned image
var followUpImageParts = followUpResponse.Candidates.First().Content.Parts
.OfType<ModelContent.InlineDataPart>()
.Where(part => part.MimeType == "image/png");
// Load the image into a Unity Texture2D object
UnityEngine.Texture2D followUpTexture2D = new(2, 2);
if (followUpTexture2D.LoadImage(followUpImageParts.First().Data.ToArray())) {
// Do something with the image
}
Cung cấp hình ảnh tham khảo
Các mô hình Gemini Nano Banana cho phép bạn cung cấp hình ảnh tham khảo trong câu lệnh. Những hình ảnh này có thể bao gồm:
Gemini Nano Banana 2.1 (
gemini-nano-banana-2.1):- Tối đa 10 hình ảnh về các đối tượng có độ chân thực cao để đưa vào hình ảnh cuối cùng
- Tối đa 4 hình ảnh nhân vật để duy trì tính nhất quán của nhân vật
Gemini Nano Banana 2 (
gemini-3.1-flash-image):- Tối đa 10 hình ảnh về các đối tượng có độ chân thực cao để đưa vào hình ảnh cuối cùng
- Tối đa 4 hình ảnh nhân vật để duy trì tính nhất quán của nhân vật
Gemini Nano Banana 2 Lite (
gemini-3.1-flash-lite-image):- Tối đa 10 hình ảnh về các đối tượng có độ chân thực cao để đưa vào hình ảnh cuối cùng
- Tối đa 4 hình ảnh nhân vật để duy trì tính nhất quán của nhân vật
Gemini Nano Banana Pro (
gemini-3-pro-image)- Tối đa 6 hình ảnh về các đối tượng có độ chính xác cao để đưa vào hình ảnh cuối cùng
- Tối đa 5 hình ảnh của nhân vật để duy trì tính nhất quán của nhân vật
- Tối đa 3 hình ảnh dùng làm hình ảnh tham khảo về phong cách
Xin lưu ý rằng mô hình gemini-2.5-flash-image chỉ hỗ trợ tối đa 3 hình ảnh.
Định cấu hình tính năng tạo hình ảnh
Theo mặc định, các mô hình Gemini Nano Banana sẽ tạo ra hình ảnh vuông (tỷ lệ khung hình 1:1) ở độ phân giải 1024x1024. Bạn có thể tuỳ chỉnh kết quả của hình ảnh tạo sinh bằng thuộc tính imageConfig trong generationConfig.
Ví dụ: bạn có thể định cấu hình hình ảnh đầu ra bằng cách sử dụng enum tỷ lệ khung hình và kích thước hình ảnh (chẳng hạn như tỷ lệ khung hình 16:9 và độ phân giải 2K, dẫn đến hình ảnh 2752x1536), như sau:
Swift
// ...
// Specify aspect ratio and image size (both optional) in an image config.
let imageConfig = ImageConfig(aspectRatio: .landscape16x9, imageSize: .size2K)
let generationConfig = GenerationConfig(
// Configure the model to respond with text (optional) and images (required).
// Include the text modality only if you want interleaved text and images in the response.
responseModalities: [.text, .image],
imageConfig: imageConfig
)
// Make sure you initialize your chosen Gemini API backend service
let model = FirebaseAI.firebaseAI().generativeModel(
modelName: "gemini-nano-banana-2.1",
generationConfig: generationConfig
)
// ...
Kotlin
// ...
val config = generationConfig {
// Configure the model to respond with text (optional) and images (required).
// Include the text modality only if you want interleaved text and images in the response.
responseModalities = listOf(ResponseModality.TEXT, ResponseModality.IMAGE)
// Specify aspect ratio and image size (both optional) in an image config.
imageConfig = imageConfig {
aspectRatio = AspectRatio.LANDSCAPE_16x9
imageSize = ImageSize.SIZE_2K
}
}
// Make sure you initialize your chosen Gemini API backend service
val model = Firebase.ai.generativeModel(
modelName = "gemini-nano-banana-2.1",
generationConfig = config
)
// ...
Java
// ...
GenerationConfig config = new GenerationConfig.Builder()
// Configure the model to respond with text (optional) and images (required).
// Include the text modality only if you want interleaved text and images in the response.
.setResponseModalities(Arrays.asList(ResponseModality.TEXT, ResponseModality.IMAGE))
// Specify aspect ratio and image size (both optional) in an image config.
.setImageConfig(
ImageConfig.builder()
.setAspectRatio(AspectRatio.LANDSCAPE_16x9)
.setImageSize(ImageSize.SIZE_2K)
.build()
)
.build();
// Make sure you initialize your chosen Gemini API backend service
GenerativeModel model = FirebaseAI.getInstance().generativeModel(
"gemini-nano-banana-2.1",
config
);
// ...
Web
import {
getGenerativeModel,
ResponseModality,
ImageConfigAspectRatio,
ImageConfigImageSize
} from "firebase/ai";
// ...
const generationConfig = {
// Configure the model to respond with text (optional) and images (required).
// Include the text modality only if you want interleaved text and images in the response.
responseModalities: [ResponseModality.TEXT, ResponseModality.IMAGE],
// Specify aspect ratio and image size (both optional) in an image config.
imageConfig: {
aspectRatio: ImageConfigAspectRatio.LANDSCAPE_16x9,
imageSize: ImageConfigImageSize.SIZE_2K
}
};
// Make sure you initialize your chosen Gemini API backend service
const model = getGenerativeModel(ai, {
model: "gemini-nano-banana-2.1",
generationConfig
});
// ...
Dart
// ...
final generationConfig = GenerationConfig(
// Configure the model to respond with text (optional) and images (required).
// Include the text modality only if you want interleaved text and images in the response.
responseModalities: [ResponseModalities.text, ResponseModalities.image],
// Specify aspect ratio and image size (both optional) in an image config.
imageConfig: ImageConfig(
aspectRatio: ImageAspectRatio.landscape16x9,
imageSize: ImageSize.size2K,
),
);
// Make sure you initialize your chosen Gemini API backend service
final model = FirebaseAI.instance.generativeModel(
model: 'gemini-nano-banana-2.1,
generationConfig: generationConfig,
);
// ...
Unity
// ...
var generationConfig = new GenerationConfig(
// Configure the model to respond with text (optional) and images (required).
// Include the text modality only if you want interleaved text and images in the response.
responseModalities: new[] { ResponseModality.Text, ResponseModality.Image },
// Specify aspect ratio and image size (both optional) in an image config.
imageConfig: new ImageConfig(
aspectRatio: ImageConfig.AspectRatio.Landscape16x9,
imageSize: ImageConfig.ImageSize.Size2K)
);
// Make sure you initialize your chosen Gemini API backend service.
var model = FirebaseAI.GetInstance().GetGenerativeModel(
modelName: "gemini-nano-banana-2.1",
generationConfig: generationConfig
);
// ...
Tỷ lệ khung hình được hỗ trợ
Tất cả các mô hình Gemini Nano Banana đều hỗ trợ các tỷ lệ khung hình sau:
Mặc định: 1:1 (hình vuông)
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
Kích thước hình ảnh được hỗ trợ (độ phân giải)
Kích thước hình ảnh (độ phân giải) được hỗ trợ phụ thuộc vào mô hình bạn đang sử dụng.
| Dòng Gemini Nano Banana. | Kích thước (độ phân giải) được hỗ trợ |
|---|---|
Gemini Nano Banana 2.1gemini-nano-banana-2.1
|
Mặc định: 1K (1024)1K (1024), 2K (2048), 4K (4096)
|
Gemini Nano Banana 2gemini-3.1-flash-image
|
Mặc định: 1K (1024)512, 1K (1024), 2K (2048), 4K (4096)
|
Gemini Nano Banana 2 Litegemini-3.1-flash-lite-image
|
Mặc định: 1K (1024)512 (chỉ Gemini Developer API), 1K (1024)
|
Gemini Nano Banana Progemini-3-pro-image
|
Mặc định: 1K (1024)1K (1024), 2K (2048), 4K (4096)
|
Bạn phải sử dụng hậu tố K viết hoa (tức là 1K, 2K, 4K).
Giá trị 512 không sử dụng hậu tố K.
Hậu tố k viết thường (ví dụ: 1k) sẽ bị từ chối.
Xin lưu ý rằng mô hình gemini-2.5-flash-image được cố định ở 1K (1024).
Tính năng được hỗ trợ
Sau đây là các tính năng được hỗ trợ, chẳng hạn như phương thức, công cụ, dữ liệu đầu vào và ngôn ngữ.
Để biết tỷ lệ khung hình và độ phân giải được hỗ trợ cho từng mô hình, hãy xem phần Định cấu hình tính năng tạo hình ảnh ở phần trước của hướng dẫn này.
Các phương thức được hỗ trợ
Sau đây là các "phương thức" được hỗ trợ cho các mô hình Gemini Nano Banana. Những "phương thức" này không được đặt rõ ràng trong yêu cầu của bạn. Chúng giống như các mẫu được đề xuất cho các trường hợp sử dụng phổ biến. Mỗi phương thức trong danh sách này đều có một câu lệnh mẫu và một đoạn mã mẫu ở phần trước của hướng dẫn này.
Văn bản (Các) hình ảnh (chỉ văn bản thành hình ảnh)
- Tạo hình ảnh tháp Eiffel có pháo hoa ở phía sau.
Văn bản (Các) hình ảnh (kết xuất văn bản trong hình ảnh)
- Tạo ảnh có hiệu ứng điện ảnh về một toà nhà lớn có dòng chữ khổng lồ này được chiếu lên mặt trước của toà nhà.
Chỉnh sửa hình ảnh (văn bản và hình ảnh thành hình ảnh)
[hình ảnh bánh nướng] + Chỉnh sửa hình ảnh này để trông giống như phim hoạt hình
[hình ảnh một chú mèo] + [hình ảnh một chiếc gối] + Tạo một bức tranh thêu chữ thập hình chú mèo của tôi trên chiếc gối này.
Video và văn bản (Các) hình ảnh (chuyển văn bản và video thành hình ảnh)
- [video/URL của một công viên] + Tạo một hình ảnh áp phích thể hiện các chủ đề chính của video này.
Văn bản (Các) hình ảnh và văn bản (xen kẽ)
Tạo công thức nấu món cơm thập cẩm paella có hình minh hoạ. Tạo hình ảnh cùng với văn bản khi bạn tạo công thức.
Tạo một câu chuyện về một chú chó theo phong cách hoạt hình 3D. Tạo hình ảnh cho mỗi cảnh.
(Các) hình ảnh và văn bản (Các) hình ảnh và văn bản (xen kẽ)
- [hình ảnh một căn phòng có đồ nội thất] + Những màu ghế sofa nào khác sẽ phù hợp với không gian của tôi? Bạn có thể cập nhật hình ảnh không?
Chỉnh sửa hình ảnh nhiều lượt (trò chuyện)
- [hình ảnh một chiếc ô tô màu xanh dương] + Biến chiếc ô tô này thành ô tô mui trần., sau đó Giờ thì đổi màu thành màu vàng.
Công cụ được hỗ trợ
Hỗ trợ
Căn cứ vào
Gemini Nano Banana 2.1 (
gemini-nano-banana-2.1)Gemini Nano Banana 2 (
gemini-3.1-flash-image)Gemini Nano Banana Pro (
gemini-3-pro-image)
Các chức năng khác được hỗ trợ
Thông tin đầu vào đa phương thức được hỗ trợ:
Hình ảnh đầu vào: Tất cả các mô hình Nano Banana.
Đầu vào video:
- Gemini Nano Banana 2.1 (
gemini-nano-banana-2.1) - Gemini Nano Banana 2 (
gemini-3.1-flash-image) - Gemini Nano Banana 2 Lite (
gemini-3.1-flash-lite-image)
- Gemini Nano Banana 2.1 (
Đầu vào âm thanh: Không có mô hình Nano Banana nào.
Tất cả các mô hình Nano Banana đều hỗ trợ những tính năng sau:
- Đang tạo hình ảnh PNG.
- Tạo và chỉnh sửa hình ảnh người.
- Sử dụng các bộ lọc an toàn mang lại trải nghiệm linh hoạt và ít hạn chế hơn cho người dùng.
Hỗ trợ tạo kết quả có cấu trúc (như JSON):
- Gemini Nano Banana Pro (
gemini-3-pro-image)
- Gemini Nano Banana Pro (
Ngôn ngữ được hỗ trợ
Mặc dù các mô hình Gemini Nano Banana có thể chấp nhận câu lệnh văn bản bằng nhiều ngôn ngữ, nhưng các ngôn ngữ được liệt kê trong phần này sẽ mang lại hiệu suất tốt nhất.
Dưới đây là các ngôn ngữ được hỗ trợ cho câu lệnh văn bản và văn bản trong hình ảnh tạo sinh:
ar-EG, de-DE, EN, es-MX, fr-FR, hi-IN, id-ID, it-IT,
ja-JP, ko-KR, pt-BR, ru-RU, uk-UA, vi-VN, zh-CN
Để sử dụng một ngôn ngữ cụ thể trong hình ảnh được tạo (ngay cả khi không có mã ngôn ngữ), bạn chỉ cần yêu cầu mô hình trong câu lệnh (ví dụ: "Cập nhật bản đồ hoạ thông tin này sang tiếng Tây Ban Nha. Đừng thay đổi bất kỳ thành phần nào khác của hình ảnh.").
Xin lưu ý rằng mô hình gemini-2.5-flash-image chỉ hỗ trợ EN, es-MX, ja-JP, zh-CN, hi-IN trong câu lệnh văn bản và chỉ có thể tạo tiếng Anh trong hình ảnh.
Các phương pháp hay nhất
Sau đây là các phương pháp hay nhất cho mô hình Gemini Nano Banana.
Khi tạo hình ảnh có chứa văn bản, trước tiên, hãy tạo văn bản rồi tạo hình ảnh có văn bản đó.
Tính năng tạo hình ảnh không phải lúc nào cũng được kích hoạt. Ngoài ra, tính năng tạo hình ảnh hoặc văn bản có thể không hoạt động như mong đợi trong những trường hợp sau:
Mô hình có thể chỉ tạo văn bản do AI tạo mà không tạo hình ảnh (đặc biệt nếu câu lệnh không rõ ràng). Nếu điều này xảy ra,
FinishReasonsẽ làNO_IMAGE.
Hãy thử yêu cầu rõ ràng về kết quả hình ảnh. Ví dụ: "tạo hình ảnh", "cung cấp hình ảnh trong quá trình thực hiện", "cập nhật hình ảnh".Mô hình có thể ngừng tạo giữa chừng.
Hãy thử lại hoặc thử một câu lệnh khác.Mô hình có thể tạo văn bản dưới dạng hình ảnh.
Hãy thử yêu cầu rõ ràng về kết quả dạng văn bản. Ví dụ: "tạo văn bản tường thuật cùng với hình minh hoạ".Nếu một câu lệnh có khả năng không an toàn, mô hình có thể không xử lý yêu cầu và thay vào đó, trả về một phản hồi cho biết rằng mô hình không thể tạo hình ảnh không an toàn. Nếu điều này xảy ra,
FinishReasonsẽ làSTOP.