Genera y edita imágenes con Gemini (también conocido como "Nano Banana")


Puedes pedirle a un modelo de imagen de Gemini que genere y edite imágenes con instrucciones de solo texto y de texto y archivo. Cuando usas Firebase AI Logic, puedes realizar esta solicitud directamente desde tu app.

Con esta función, puedes hacer lo siguiente:

  • Genera imágenes de forma iterativa a través de conversaciones con lenguaje natural, ajustando las imágenes mientras se mantiene la coherencia y el contexto.

  • Genera imágenes con renderización de texto de alta calidad, incluidas cadenas de texto largas.

  • Genera resultados intercalados de texto e imágenes. Por ejemplo, una entrada de blog con texto e imágenes en un solo turno. Anteriormente, esto requería encadenar varios modelos.

  • Genera imágenes con el conocimiento del mundo y las capacidades de razonamiento de Gemini.

Puedes configurar la modalidad de respuesta para tu solicitud de modo que el modelo genere solo imágenes o imágenes y texto. Encuentra una lista completa de las funciones compatibles (junto con instrucciones de ejemplo) más adelante en esta página.

Ir al código para texto a imagen Ir al código para texto e imágenes intercalados

Ir al código para editar imágenes Ir al código para editar imágenes de forma iterativa


Consulta otras guías para conocer opciones adicionales para trabajar con imágenes
Analiza imágenes Analiza imágenes integrado en el dispositivo Genera resultados estructurados

Antes de comenzar

Haz clic en tu proveedor de Gemini API para ver el contenido y el código específicos del proveedor en esta página.

Si aún no lo hiciste, completa la guía de introducción, en la que se describe cómo configurar tu proyecto de Firebase, conectar tu app a Firebase, agregar el SDK, inicializar el servicio de backend para el proveedor de Gemini API que elijas y crear una instancia de GenerativeModel.

Para probar y, luego, iterar tus instrucciones, te recomendamos usar Google AI Studio.

Modelos que admiten esta capacidad

  • gemini-3-pro-image (también conocido como "Nano Banana Pro")
  • gemini-3.1-flash-image (también conocido como "Nano Banana 2")
  • gemini-3.1-flash-lite-image (también conocido como "Nano Banana 2 Lite")

Los modelos Gemini 2.5 que generan imágenes admiten esta capacidad, pero todos dejaron de estar disponibles.

Generar y editar imágenes

Puedes generar y editar imágenes con un modelo de Gemini.

Genera imágenes (entrada de solo texto)

Antes de probar esta muestra, completa la sección Antes de comenzar de esta guía para configurar tu proyecto y tu app.
En esa sección, también harás clic en un botón para el proveedor de Gemini API que elijas, de modo que veas el contenido específico del proveedor en esta página.

Puedes pedirle a un modelo de Imagen de Gemini que genere imágenes con instrucciones de texto.

Crea una instancia de GenerativeModel, incluye la modalidad de respuesta de IMAGE en la configuración del modelo y llama a 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-3.1-flash-image",
  // 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-3.1-flash-image",
    // 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-3.1-flash-image",
    // 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-3.1-flash-image",
  // 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-3.1-flash-image',
  // 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-3.1-flash-image",
  // 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);

var text = response.Text;
if (!string.IsNullOrWhiteSpace(text)) {
  // Do something with the text
}

// 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
  }
}

Genera imágenes y texto intercalado

Antes de probar esta muestra, completa la sección Antes de comenzar de esta guía para configurar tu proyecto y tu app.
En esa sección, también harás clic en un botón para el proveedor de Gemini API que elijas, de modo que veas el contenido específico del proveedor en esta página.

Puedes pedirle a un modelo de Gemini Imagen que genere imágenes intercaladas con sus respuestas de texto. Por ejemplo, puedes generar imágenes de cómo se vería cada paso de una receta generada junto con las instrucciones del paso, y no tienes que hacer solicitudes separadas al modelo ni a diferentes modelos.

Crea una instancia de GenerativeModel, incluye las modalidades de respuesta de TEXT y IMAGE en la configuración del modelo y llama a 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-3.1-flash-image",
  // 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-3.1-flash-image",
    // 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-3.1-flash-image",
    // 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-3.1-flash-image",
  // 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-3.1-flash-image',
  // 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.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-3.1-flash-image",
  // 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
      }
    }
  }
}

Edita imágenes (entrada de texto e imagen)

Antes de probar esta muestra, completa la sección Antes de comenzar de esta guía para configurar tu proyecto y tu app.
En esa sección, también harás clic en un botón para el proveedor de Gemini API que elijas, de modo que veas contenido específico del proveedor en esta página.

Puedes pedirle a un modelo de imagen de Gemini que edite imágenes con instrucciones de texto y una o más imágenes.

Crea una instancia de GenerativeModel, incluye la modalidad de respuesta de IMAGE en la configuración de tu modelo y llama a 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-3.1-flash-image",
  // 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-3.1-flash-image",
    // 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-3.1-flash-image",
    // 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-3.1-flash-image",
  // 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-3.1-flash-image',
  // 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-3.1-flash-image",
  // 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 });

var text = response.Text;
if (!string.IsNullOrWhiteSpace(text)) {
  // Do something with the text
}

// 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
  }
}

Itera y edita imágenes con un chat de varios turnos

Antes de probar esta muestra, completa la sección Antes de comenzar de esta guía para configurar tu proyecto y tu app.
En esa sección, también harás clic en un botón para el proveedor de Gemini API que elijas, de modo que veas contenido específico del proveedor en esta página.

Con el chat de varios turnos, puedes iterar con un modelo de imagen Gemini en las imágenes que genera o que proporcionas.

Crea una instancia de GenerativeModel, incluye la modalidad de respuesta de IMAGE en la configuración de tu modelo y llama a startChat() y sendMessage() para enviar mensajes de usuario nuevos.

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-3.1-flash-image",
  // 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-3.1-flash-image",
    // 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-3.1-flash-image",
    // 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-3.1-flash-image",
  // 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-3.1-flash-image',
  // 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-3.1-flash-image",
  // 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
}



Proporciona imágenes de referencia

Gemini Los modelos de imágenes te permiten proporcionar imágenes de referencia en tu instrucción. Esto incluye las siguientes imágenes:

  • Gemini 3.x Pro Image (gemini-3-pro-image, también conocido como "Nano Banana Pro")

    • Hasta 6 imágenes de objetos con alta fidelidad para incluir en la imagen final
    • Hasta 5 imágenes de personajes para mantener la continuidad de los personajes
    • Hasta 3 imágenes para usar como referencias de estilo
  • Gemini 3.x Flash Image (gemini-3.1-flash-image, también conocido como "Nano Banana 2"):

    • Hasta 10 imágenes de objetos con alta fidelidad para incluir en la imagen final
    • Hasta 4 imágenes de personajes para mantener la continuidad de los personajes
  • Gemini 3.x Flash‑Lite Image (gemini-3.1-flash-lite-image, también conocido como "Nano Banana 2 Lite"):

    • Hasta 10 imágenes de objetos con alta fidelidad para incluir en la imagen final
    • Hasta 4 imágenes de personajes para mantener la continuidad de los personajes
  • Gemini 2.5 Flash Image (gemini-2.5-flash-image, también conocido como "Nano Banana"):

    • Hasta 3 imágenes

Configura la generación de imágenes

De forma predeterminada, los modelos de Image de Gemini generan imágenes cuadradas (relación de aspecto de 1:1) con una resolución de 1024 x 1024. Puedes personalizar el resultado de las imágenes generadas con la propiedad imageConfig dentro de generationConfig.

Por ejemplo, puedes configurar la imagen de salida con las enumeraciones de relación de aspecto y tamaño de imagen (como una relación de aspecto de 16:9 y una resolución de 2K, lo que da como resultado una imagen de 2752 x 1536), de la siguiente manera:

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-3.1-flash-image",
  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-3.1-flash-image",
    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-3.1-flash-image",
    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-3.1-flash-image",
  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-3.1-flash-image,
  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-3.1-flash-image",
  generationConfig: generationConfig
);

// ...

Relaciones de aspecto compatibles

Todos los modelos de imagen de Gemini admiten las siguientes relaciones de aspecto:

Valor predeterminado: 1:1 (cuadrado)

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

Tamaños de imagen (resoluciones) compatibles

Los tamaños de imagen (resoluciones) admitidos dependen del modelo que uses.

Gemini Modelo de imagen Tamaños (resoluciones) admitidos
Gemini 3.x Pro Image
gemini-3-pro-image
("Nano Banana Pro")
Valor predeterminado: 1K (1024)
1K (1024), 2K (2048), 4K (4096)
Gemini 3.x Flash Image
gemini-3.1-flash-image
("Nano Banana 2")
Valor predeterminado: 1K (1,024)
512, 1K (1,024), 2K (2,048), 4K (4,096)
Gemini 3.x Flash‑Lite Image
gemini-3.1-flash-lite-image
("Nano Banana 2 Lite")
Valor predeterminado: 1K (1,024)
512 (solo Gemini Developer API), 1K (1,024)
Gemini 2.5 Flash Image
gemini-2.5-flash-image
("Nano Banana")
Fijo en 1K (1024)

Debes usar un sufijo K en mayúsculas (es decir, 1K, 2K, 4K). El valor 512 no usa un sufijo K. Se rechazará un sufijo k en minúsculas (por ejemplo, 1k).



Funciones admitidas

Las siguientes son funciones compatibles, como modalidades, herramientas, entradas y lenguajes.

Para conocer las relaciones de aspecto y las resoluciones admitidas para cada modelo, consulta Configura la generación de imágenes más arriba en esta guía.

Modalidades compatibles

Las siguientes son las "modalidades" admitidas para los modelos de imagen de Gemini. Estas "modalidades" no se establecen de forma explícita en tus solicitudes. Son más bien patrones recomendados para casos de uso comunes. Cada modalidad de esta lista muestra una instrucción de ejemplo y tiene una muestra de código de ejemplo que se mostró antes en esta guía.

  • Texto Imágenes (solo texto a imagen)

    • Genera una imagen de la Torre Eiffel con fuegos artificiales de fondo.
  • Texto Imágenes (renderización de texto dentro de la imagen)

    • Genera una foto cinemática de un edificio grande con esta proyección de texto gigante en el frente.
  • Texto Imágenes y texto (intercalados)

    • Genera una receta ilustrada de paella. Crea imágenes junto con el texto mientras generas la receta.

    • Genera una historia sobre un perro con un estilo de animación de dibujos animados en 3D. Genera una imagen para cada escena.

  • Imágenes y texto Imágenes y texto (intercalados)

    • [Imagen de una habitación amueblada] + ¿Qué otros colores de sofás funcionarían en mi espacio? ¿Puedes actualizar la imagen?
  • Edición de imágenes (de texto e imagen a imagen)

    • [Imagen de scones] + Edita esta imagen para que parezca una caricatura

    • [imagen de un gato] + [imagen de un almohadón] + Crea un punto de cruz de mi gato en este almohadón.

  • Edición de imágenes de varios turnos (chat)

    • [Imagen de un automóvil azul] + Convierte este automóvil en un convertible y, luego, Ahora cambia el color a amarillo.

Herramientas compatibles

Asistencia para la fundamentación con Google Search:

  • Gemini 3.x Pro Image (gemini-3-pro-image, también conocido como "Nano Banana Pro")

  • Gemini 3.x Flash Image (gemini-3.1-flash-image, también conocido como "Nano Banana 2")

Otras funciones compatibles

  • Entrada multimodal admitida:

    • Entrada de imagen: Todos los modelos de Gemini Image

    • Entrada de video:

      • Gemini 3.x Flash Image (gemini-3.1-flash-image, también conocido como "Nano Banana 2")
      • Gemini 3.x Flash‑Lite Image (gemini-3.1-flash-lite-image, también conocido como "Nano Banana 2 Lite")
    • Entrada de audio: Ninguno de los modelos de Gemini Image.

  • Todos los modelos de imágenes de Gemini admiten lo siguiente:

    • Generando imágenes PNG.
    • Generar y editar imágenes de personas
    • Usar filtros de seguridad que proporcionen una experiencia del usuario flexible y menos restrictiva
  • Compatibilidad con la generación de resultados estructurados (como JSON):

    • Gemini 3.x Pro Image (gemini-3-pro-image, también conocido como "Nano Banana Pro")

Lenguajes compatibles

Si bien los modelos de imagen de Gemini pueden aceptar instrucciones de texto en muchos idiomas, los idiomas que se indican en esta sección te brindarán el mejor rendimiento.

  • Idiomas compatibles con la instrucción de texto:

    • Modelos de Gemini 3.x Image: 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
    • Modelo Gemini 2.5 Flash Image: EN, es-MX, ja-JP, zh-CN, hi-IN.
  • Idiomas compatibles con el texto de la imagen creada con tecnología generativa:

    • Modelos Gemini 3.x Image: los mismos idiomas que en la lista anterior
    • Modelo Gemini 2.5 Flash Image: solo en inglés

    Para usar un idioma específico en una imagen creada con tecnología generativa (incluso sin el código de idioma), solo pídele al modelo en tu instrucción (por ejemplo, "Actualiza esta infografía para que esté en español. No cambies ningún otro elemento de la imagen").



Prácticas recomendadas

A continuación, se indican las prácticas recomendadas para los modelos de imágenes Gemini.

  • Cuando generes una imagen que contenga texto, primero genera el texto y, luego, genera una imagen con ese texto.

  • Es posible que la generación de imágenes no siempre se active. Además, es posible que la generación de imágenes o texto no funcione como se espera en las siguientes situaciones:

    • Es posible que el modelo solo genere texto y no una imagen (en especial, si la instrucción es ambigua). Si esto sucede, el FinishReason es NO_IMAGE.
      Intenta pedir explícitamente que se generen imágenes. Por ejemplo, "genera una imagen", "proporciona imágenes a medida que avanzas", "actualiza la imagen".

    • Es posible que el modelo deje de generar contenido a mitad de camino.
      Vuelve a intentarlo o prueba con otra instrucción.

    • El modelo puede generar texto como una imagen.
      Intenta pedir resultados de texto de forma explícita. Por ejemplo, "genera texto narrativo junto con ilustraciones".

    • Si una instrucción es potencialmente insegura, es posible que el modelo no procese la solicitud y, en su lugar, devuelva una respuesta que indique que no puede crear imágenes no seguras. Si esto sucede, el FinishReason es STOP.