所有 Imagen 模型將於 2026 年 8 月 17 日停用。這項終止服務適用於 Google 旗下所有服務,以及 Gemini Developer API 和 Agent Platform Gemini API (formerly Vertex AI)。
如要繼續在應用程式中生成或編輯圖片,請按照本指南所述,從使用 Imagen 模型遷移至使用 Gemini Nano Banana 模型。
如果這項淘汰和停用作業造成緊急問題,請聯絡 Firebase 支援團隊。
替代 Nano Banana 模型
下表可協助您為應用程式選擇替代 Nano Banana 模型。
| Imagen 個模型 | Gemini Nano Banana 個模型 |
|---|---|
imagen-4.0-fast-generate-001 |
gemini-nano-banana-2.1 (思考等級:MINIMAL) |
imagen-4.0-generate-001 |
gemini-nano-banana-2.1 (思考等級:HIGH) |
imagen-4.0-ultra-generate-001 |
gemini-3-pro-image
|
imagen-3.0-capability-001 |
gemini-nano-banana-2.1
|
遷移應用程式
本節提供從 Imagen 模型遷移至 Gemini Nano Banana 模型的前後範例。
根據文字生成圖片
|
按一下您的Gemini API供應商,即可在這個頁面查看供應商專屬內容和程式碼。 |
如要根據文字生成圖片,請對應用程式進行以下變更,完成遷移:
使用適當的替代 Nano Banana 模型 (例如
gemini-nano-banana-2.1)。建立
GenerativeModel執行個體 (而非ImagenModel執行個體)。更新模型設定選項,以容納 Nano Banana 模型。
- 設定時,請將回應模態設為
IMAGE。
請注意,Nano Banana 模型可設為同時傳回圖片和文字。
- 設定時,請將回應模態設為
Swift
之前
import FirebaseAILogic
// Initialize the Gemini Developer API backend service.
let ai = FirebaseAI.firebaseAI(backend: .googleAI())
// Create an `ImagenModel` instance with a model that supports your use case.
let model = ai.imagenModel(modelName: "IMAGEN_MODEL_NAME")
// Provide an image generation prompt.
let prompt = "An astronaut riding a horse"
// To generate an image, call `generateImages` with the text prompt.
let response = try await model.generateImages(prompt: prompt)
// Handle the generated image.
guard let image = response.images.first else {
fatalError("No image in the response.")
}
let uiImage = UIImage(data: image.data)
之後
import FirebaseAILogic
// Initialize the Gemini Developer API backend service.
let ai = FirebaseAI.firebaseAI(backend: .googleAI())
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
let model = ai.generativeModel(
modelName: "GEMINI_NANOBANANA_MODEL_NAME",
generationConfig: GenerationConfig(
responseModalities: [.image],
imageConfig: ImageConfig(aspectRatio: .landscape4x3)
)
)
// Provide an image generation prompt.
let prompt = "An astronaut riding a horse"
// To generate an image, call `generateContent` with the text prompt.
let response = try await model.generateContent(prompt)
// Handle the case where no images were generated.
guard let inlineDataPart = response.inlineDataParts.first else {
fatalError("No image in the response.")
}
// Process the image.
guard let uiImage = UIImage(data: inlineDataPart.data) else {
fatalError("Failed to convert data to UIImage.")
}
Kotlin
之前
// Initialize the Gemini Developer API backend service.
val ai = Firebase.ai(backend = GenerativeBackend.googleAI())
// Create an `ImagenModel` instance with an Imagen model that supports your use case.
val model = ai.imagenModel("IMAGEN_MODEL_NAME")
// Provide an image generation prompt.
val prompt = "An astronaut riding a horse"
// To generate an image, call `generateImages` with the text prompt.
val imageResponse = model.generateImages(prompt)
// Handle the generated image.
val image = imageResponse.images.first()
val bitmapImage = image.asBitmap()
之後
// Initialize the Gemini Developer API backend service.
val ai = Firebase.ai(backend = GenerativeBackend.googleAI())
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
val model = ai.generativeModel(
modelName = "GEMINI_NANOBANANA_MODEL_NAME",
generationConfig = generationConfig {
responseModalities = listOf(ResponseModality.IMAGE),
imageConfig = imageConfig {
aspectRatio = AspectRatio.LANDSCAPE_4x3
}
}
)
// Provide an image generation prompt.
val prompt = "An astronaut riding a horse"
// To generate an image, call `generateContent` with the text prompt.
val imageResponse = model.generateContent(prompt)
if (imageResponse.finishReason == FinishReason.NO_IMAGE) {
// Handle the case where no images were generated.
} else {
// Handle the generated image.
val bitmapImage = imageResponse.candidates.first().content.parts.filterIsInstance().firstOrNull()?.image
}
Java
之前
// Initialize the Gemini Developer API backend service.
// Create an `ImagenModel` instance with an Imagen model that supports your use case.
ImagenModel imagenModel = FirebaseAI.getInstance(GenerativeBackend.googleAI())
.imagenModel(
/* modelName */ "IMAGEN_MODEL_NAME");
ImagenModelFutures model = ImagenModelFutures.from(imagenModel);
// Provide an image generation prompt.
String prompt = "An astronaut riding a horse";
// To generate an image, call `generateImages` with the text prompt.
Futures.addCallback(model.generateImages(prompt), new FutureCallback<ImagenGenerationResponse>() {
@Override
public void onSuccess(ImagenGenerationResponse result) {
if (result.getImages().isEmpty()) {
Log.d("TAG", "No images generated");
}
Bitmap bitmap = result.getImages().get(0).asBitmap();
// Use the bitmap to display the image in your UI.
}
@Override
public void onFailure(Throwable t) {
// ...
}
}, Executors.newSingleThreadExecutor());
之後
// 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_NANOBANANA_MODEL_NAME",
new GenerationConfig.Builder()
.setResponseModalities(Arrays.asList(ResponseModality.IMAGE))
.setImageConfig(new ImageConfig(AspectRatio.LANDSCAPE_4x3, null))
.build()
);
GenerativeModelFutures model = GenerativeModelFutures.from(ai);
// Provide a text prompt instructing the model to generate an image.
Content prompt = new Content.Builder()
.addText("An astronaut riding a horse")
.build();
// To generate an image, call `generateContent` with the text input.
Executor executor = Executors.newSingleThreadExecutor();
ListenableFuture response = model.generateContent(prompt);
Futures.addCallback(response, new FutureCallback() {
@Override
public void onSuccess(GenerateContentResponse result) {
if (result.finishReason == FinishReason.NO_IMAGE) {
// handle the case where no images were generated
return;
}
// 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, getImagenModel, GoogleAIBackend } from "firebase/ai";
// TODO(developer): Replace the following with your app's Firebase configuration
const firebaseConfig = {
// ...
};
// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);
// Initialize the Gemini Developer API backend service.
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });
// Create an `ImagenModel` instance with an Imagen model that supports your use case.
const model = getImagenModel(ai, { model: "IMAGEN_MODEL_NAME" });
// Provide an image generation prompt.
const prompt = "An astronaut riding a horse.";
// To generate an image, call `generateImages` with the text prompt.
const response = await model.generateImages(prompt)
// If fewer images were generated than were requested,
// then `filteredReason` will describe the reason they were filtered out.
if (response.filteredReason) {
console.log(response.filteredReason);
}
if (response.images.length == 0) {
throw new Error("No images in the response.")
}
const image = response.images[0];
之後
import { initializeApp } from "firebase/app";
import {
getAI,
getGenerativeModel,
GoogleAIBackend,
ResponseModality,
ImageConfigAspectRatio,
FinishReason
} from "firebase/ai";
// TODO(developer): Replace the following with your app's Firebase configuration
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_NANOBANANA_MODEL_NAME",
generationConfig: {
responseModalities: [ResponseModality.IMAGE],
imageConfig: {
aspectRatio: ImageConfigAspectRatio.LANDSCAPE_4x3
}
},
});
// Provide an image generation prompt.
const prompt = "An astronaut riding a horse.";
// To generate an image, call `generateContent` with the text prompt.
const result = await model.generateContent(prompt);
// Handle the generated image.
try {
const response = result.response;
if (response.candidates?.[0].finishReason == FinishReason.NO_IMAGE) {
// Handle the case where no images were generated.
}
const inlineDataParts = response.inlineDataParts();
if (inlineDataParts?.[0]) {
const image = inlineDataParts[0].inlineData;
// Use this mimeType and base64 data to display the image using your preferred tooling.
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';
// Initialize FirebaseApp
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Initialize the Gemini Developer API backend service.
final ai = FirebaseAI.googleAI();
// Create an `ImagenModel` instance with an Imagen model that supports your use case.
final model = ai.imagenModel(model: 'IMAGEN_MODEL_NAME');
// Provide an image generation prompt.
const prompt = 'An astronaut riding a horse.';
// To generate an image, call `generateImages` with the text prompt.
final response = await model.generateImages(prompt);
if (response.images.isNotEmpty) {
final image = response.images[0];
// Process the image.
} else {
// Handle the case where no images were generated.
print('Error: No images were generated.');
}
之後
import 'package:firebase_ai/firebase_ai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
// Initialize FirebaseApp
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Initialize the Gemini Developer API backend service.
final ai = FirebaseAI.googleAI();
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
final model = ai.generativeModel(
model: 'GEMINI_NANOBANANA_MODEL_NAME',
generationConfig: GenerationConfig(
responseModalities: [ResponseModalities.image],
imageConfig: ImageConfig(aspectRatio: ImageAspectRatio.landscape4x3)
),
);
// Provide a text prompt instructing the model to generate an image.
final prompt = [Content.text('An astronaut riding a horse.')];
// To generate an image, call `generateContent` with the text prompt.
final response = await model.generateContent(prompt);
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.AI;
// Initialize the Gemini Developer API backend service
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());
// Create an `ImagenModel` instance with a model that supports your use case
var model = ai.GetImagenModel(modelName: "IMAGEN_MODEL_NAME");
// Provide an image generation prompt
var prompt = "An astronaut riding a horse";
// To generate an image, call `generateImages` with the text prompt
var response = await model.GenerateImagesAsync(prompt: prompt);
// Handle the generated image
if (response.Images.Count == 0) {
throw new Exception("No image in the response.");
}
var image = response.Images[0].AsTexture2D();
之後
using Firebase;
using Firebase.AI;
// Initialize the Gemini Developer API backend service.
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
var model = ai.GetGenerativeModel(
modelName: "GEMINI_NANOBANANA_MODEL_NAME",
generationConfig: new GenerationConfig(
responseModalities: new[] { ResponseModality.Image },
imageConfig: new ImageConfig(aspectRatio: ImageConfig.AspectRatio.Landscape4x3)
)
);
// Provide an image generation prompt.
var prompt = "An astronaut riding a horse";
// To generate an image, call `GenerateContentAsync` with the text prompt.
var response = await model.GenerateContentAsync(prompt);
if (response.Candidates.First().FinishReason == FinishReason.NoImage) {
// Handle the case where no images were generated.
}
// 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.
}
}
替代設定選項
本節說明各種模型設定選項的替代選項,協助您控管模型的回覆。
安全性設定
您可以使用 ImagenSafetySettings 設定 Imagen 模型的安全設定。不過,如果是 Nano Banana 模型,則必須改用 SafetySetting。
模型設定參數
您可以使用 ImagenGenerationConfig 設定 Imagen 模型。不過,如果是 Nano Banana 模型,則必須改用 GenerationConfig,並視需要使用巢狀 ImageConfig (2026 年 5 月初推出的 SDK 版本開始提供)。
在 GenerationConfig 中,將回覆模態設為 IMAGE (如本指南前述「之後」程式碼範例所示)。請注意,您可以視需要設定 Nano Banana 模型,同時傳回 IMAGE「和」TEXT。
下表可協助您瞭解如何將模型設定參數從 Imagen 遷移至 Nano Banana 模型:
| Imagen 個模型 | Gemini Nano Banana 個模型 |
|---|---|
addWatermark |
不支援 Nano Banana 模型一律會傳回含有 SynthID 浮水印的生成圖像。 |
aspectRatio |
在 如需程式碼範例和支援的值,請參閱 Nano Banana 模型指南中的「設定圖像生成」。 |
imageFormat |
不支援 Nano Banana 模型一律會以 PNG 格式傳回生成的圖片。 |
negativePrompt |
不支援
請注意,負面提示是舊版功能,自 |
numberOfImages |
不支援
Nano Banana 模型一律會傳回單一生成圖像。 |
personGeneration |
不支援 根據預設,Nano Banana 模型可生成人物圖像。 |