Todos los modelos de Imagen están obsoletos y dejarán de funcionar el 17 de agosto de 2026. Esta baja y cierre se aplican en todo Google y tanto para la Gemini Developer API como para la Agent Platform Gemini API (formerly Vertex AI).
Antes de esta fecha de cierre, para evitar la interrupción del servicio, debes migrar tus apps para que dejen de usar modelos Imagen y usen modelos Gemini Nano Banana, como se describe en esta guía.
Si tienes un problema urgente relacionado con esta baja y cierre, comunícate con el equipo de asistencia de Firebase.
Modelos de reemplazo de Nano Banana
La siguiente tabla puede ayudarte a elegir un modelo de Nano Banana de reemplazo para tu app.
| en Imagen modelo | Gemini Nano Banana modelos |
|---|---|
imagen-4.0-fast-generate-001 |
gemini-nano-banana-2.1 (con nivel de razonamiento
MINIMAL)
|
imagen-4.0-generate-001 |
gemini-nano-banana-2.1 (con nivel de razonamiento
HIGH)
|
imagen-4.0-ultra-generate-001 |
gemini-3-pro-image
|
imagen-3.0-capability-001 |
gemini-nano-banana-2.1
|
Migra la app
En esta sección, se muestran ejemplos de antes y después de migrar de un modelo de Imagen a un modelo de Gemini Nano Banana.
Genera una imagen a partir de texto
|
Haz clic en tu proveedor de Gemini API para ver el contenido y el código específicos del proveedor en esta página. |
Para generar una imagen a partir de texto, migra tu app con los siguientes cambios:
Usa un modelo Nano Banana de reemplazo adecuado (como
gemini-nano-banana-2.1).Crea una instancia de
GenerativeModel(en lugar de una instancia deImagenModel).Actualiza las opciones de configuración del modelo para que se adapten a los modelos de Nano Banana.
- Como parte de esta configuración, establece una modalidad de respuesta de
IMAGE.
Ten en cuenta que los modelos Nano Banana se pueden configurar para devolver imágenes y texto.
- Como parte de esta configuración, establece una modalidad de respuesta de
Swift
Antes
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)
Después
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
Antes
// 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()
Después
// 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
Antes
// 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());
Después
// 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
Antes
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];
Después
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
Antes
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.');
}
Después
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
Antes
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();
Después
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.
}
}
Opciones de configuración de reemplazo
En esta sección, se describen las opciones de reemplazo para varias opciones de configuración del modelo que ayudan a controlar la respuesta del modelo.
Configuración de seguridad
Establece la configuración de seguridad para los modelos de Imagen con
ImagenSafetySettings. Sin embargo, para los modelos de Nano Banana,
debes migrar al uso de
SafetySetting.
Parámetros de configuración del modelo
Los modelos de Imagen se configuran con un ImagenGenerationConfig. Sin embargo,
para los modelos Nano Banana, debes migrar al uso de un
GenerationConfig y, de forma opcional, un
ImageConfig
anidado (esto está disponible a partir de las versiones de principios de mayo de 2026 de los SDK).
Como parte de GenerationConfig, establece una modalidad de respuesta de IMAGE (como se muestra
en las muestras de código "después" que aparecen antes en esta guía). Ten en cuenta que, de manera opcional, puedes
configurar los modelos de Nano Banana para que devuelvan
IMAGE y TEXT.
La siguiente tabla puede ayudarte a comprender cómo migrar los parámetros de configuración de tu modelo de Imagen a Nano Banana:
| Imagen modelos | Gemini Nano Banana modelos |
|---|---|
addWatermark |
No compatible Los modelos Nano Banana siempre devuelven imágenes creadas con tecnología generativa con una marca de agua de SynthID. |
aspectRatio |
Usa Para obtener muestras de código y valores admitidos, consulta Configura la generación de imágenes en la guía de modelos de Nano Banana. |
imageFormat |
No compatible Los modelos Nano Banana siempre devuelven imágenes creadas con tecnología generativa en formato PNG. |
negativePrompt |
No compatible
Ten en cuenta que las instrucciones negativas son una función heredada y no se admiten
desde |
numberOfImages |
No compatible
Los modelos Nano Banana siempre devuelven una sola
imagen creada con tecnología generativa.
|
personGeneration |
No compatible De forma predeterminada, los modelos de Nano Banana permiten generar imágenes de personas. |