Générer et modifier des images avec Gemini Nano Banana


Vous pouvez demander à un modèle Gemini Nano Banana de générer et de modifier des images à l'aide de requêtes textuelles et de requêtes texte et fichier. Lorsque vous utilisez Firebase AI Logic, vous pouvez effectuer cette demande directement depuis votre application.

Cette fonctionnalité vous permet d'effectuer les opérations suivantes :

  • Générez des images de manière itérative par le biais d'une conversation en langage naturel, en ajustant les images tout en maintenant la cohérence et le contexte.

  • Générez des images avec un rendu de texte de haute qualité, y compris de longues chaînes de texte.

  • Générer une sortie texte-image entrelacée. Par exemple, un article de blog contenant du texte et des images en une seule requête. Auparavant, cela nécessitait d'enchaîner plusieurs modèles.

  • Générez des images en utilisant les connaissances du monde et les capacités de raisonnement de Gemini.

Vous pouvez configurer la modalité de réponse de votre requête afin que le modèle ne génère que des images, ou des images et du texte. Vous trouverez une liste complète des fonctionnalités compatibles (ainsi que des exemples de requêtes) plus bas sur cette page.


Accéder au code pour la conversion de texte en image Accéder au code pour la conversion de vidéo en image Accéder au code pour l'entrelacement de texte et d'images

Accéder au code pour la modification d'images Accéder au code pour la modification d'images itérative


Consultez d'autres guides pour découvrir d'autres options d'utilisation des images
Analyser des images Analyser des images sur l'appareil Générer une sortie structurée

Avant de commencer

Cliquez sur votre fournisseur Gemini API pour afficher le contenu et le code spécifiques au fournisseur sur cette page.

Si ce n'est pas déjà fait, suivez le guide de démarrage, qui explique comment configurer votre projet Firebase, connecter votre application à Firebase, ajouter le SDK, initialiser le service de backend pour le fournisseur Gemini API de votre choix et créer une instance GenerativeModel.

Pour tester et effectuer des itérations de vos requêtes, nous vous recommandons d'utiliser Google AI Studio.

Modèles compatibles avec cette fonctionnalité

  • 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)

Le modèle gemini-2.5-flash-image est compatible avec cette fonctionnalité, mais il est obsolète.

Générer et modifier des images

Vous pouvez générer et modifier des images à l'aide d'un modèle Gemini Nano Banana.

Générer des images (entrée textuelle uniquement)

Avant d'essayer cet exemple, suivez les instructions de la section Avant de commencer de ce guide pour configurer votre projet et votre application.
Dans cette section, vous cliquerez également sur un bouton correspondant au fournisseur Gemini API de votre choix afin d'afficher le contenu spécifique à ce fournisseur sur cette page.

Vous pouvez demander à un modèle Gemini Nano Banana de générer des images en lui fournissant un prompt textuel.

Créez une instance GenerativeModel, incluez la modalité de réponse IMAGE dans la configuration de votre modèle, puis appelez 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
  }
}

Modifier des images (entrée de texte et d'image)

Avant d'essayer cet exemple, suivez les instructions de la section Avant de commencer de ce guide pour configurer votre projet et votre application.
Dans cette section, vous cliquerez également sur un bouton correspondant au fournisseur Gemini API de votre choix afin d'afficher le contenu spécifique à ce fournisseur sur cette page.

Vous pouvez demander à un modèle Gemini Nano Banana de modifier des images en lui fournissant un prompt contenant du texte et une ou plusieurs images.

Créez une instance GenerativeModel, incluez la modalité de réponse IMAGE dans la configuration de votre modèle, puis appelez 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
  }
}

Générer des images à partir d'une entrée vidéo (entrée texte et vidéo)

Avant d'essayer cet exemple, suivez les instructions de la section Avant de commencer de ce guide pour configurer votre projet et votre application.
Dans cette section, vous cliquerez également sur un bouton correspondant au fournisseur Gemini API de votre choix afin d'afficher le contenu spécifique à ce fournisseur sur cette page.

Vous pouvez demander à un modèle Gemini Nano Banana de générer des images en lui fournissant un prompt contenant du texte et une vidéo.

Créez une instance GenerativeModel, incluez la modalité de réponse IMAGE dans la configuration de votre modèle, puis appelez 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.
  }
}

Générez du texte entrecoupé d'images

Avant d'essayer cet exemple, suivez les instructions de la section Avant de commencer de ce guide pour configurer votre projet et votre application.
Dans cette section, vous cliquerez également sur un bouton correspondant au fournisseur Gemini API de votre choix afin d'afficher le contenu spécifique à ce fournisseur sur cette page.

Vous pouvez demander à un modèle Gemini Nano Banana de générer des images entrelacées avec ses réponses textuelles. Par exemple, vous pouvez générer des images de ce à quoi pourrait ressembler chaque étape d'une recette générée, ainsi que les instructions de l'étape, sans avoir à envoyer des requêtes distinctes au modèle ou à différents modèles.

Créez une instance GenerativeModel, incluez les modalités de réponse TEXT et IMAGE dans la configuration de votre modèle, puis appelez 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
      }
    }
  }
}

Itérer et modifier des images à l'aide du chat multitour

Avant d'essayer cet exemple, suivez les instructions de la section Avant de commencer de ce guide pour configurer votre projet et votre application.
Dans cette section, vous cliquerez également sur un bouton correspondant au fournisseur Gemini API de votre choix afin d'afficher le contenu spécifique à ce fournisseur sur cette page.

Le chat multitour vous permet d'itérer avec un modèle Gemini Nano Banana sur les images qu'il génère ou que vous fournissez.

Créez une instance GenerativeModel, incluez la modalité de réponse IMAGE dans la configuration de votre modèle, puis appelez startChat() et sendMessage() pour envoyer de nouveaux messages utilisateur.

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
}



Fournir des images de référence

Les modèles Gemini Nano Banana vous permettent de fournir des images de référence dans votre prompt. Ces images peuvent inclure les éléments suivants :

  • Gemini Nano Banana 2.1 (gemini-nano-banana-2.1) :

    • Jusqu'à 10 images d'objets haute fidélité à inclure dans l'image finale
    • Jusqu'à quatre images de personnages pour maintenir la cohérence des personnages
  • Gemini Nano Banana 2 (gemini-3.1-flash-image) :

    • Jusqu'à 10 images d'objets haute fidélité à inclure dans l'image finale
    • Jusqu'à quatre images de personnages pour maintenir la cohérence des personnages
  • Gemini Nano Banana 2 Lite (gemini-3.1-flash-lite-image) :

    • Jusqu'à 10 images d'objets haute fidélité à inclure dans l'image finale
    • Jusqu'à quatre images de personnages pour maintenir la cohérence des personnages
  • Gemini Nano Banana Pro (gemini-3-pro-image)

    • Jusqu'à six images d'objets haute fidélité à inclure dans l'image finale
    • Jusqu'à cinq images de personnages pour maintenir la cohérence des personnages
    • Jusqu'à trois images à utiliser comme références de style

Notez que le modèle gemini-2.5-flash-image n'accepte que trois images au maximum.

Configurer la génération d'images

Par défaut, les modèles Gemini Nano Banana génèrent des images carrées (format 1:1) en résolution 1024 x 1024. Vous pouvez personnaliser le résultat de vos images générées à l'aide de la propriété imageConfig dans generationConfig.

Par exemple, vous pouvez configurer l'image de sortie à l'aide d'énumérations de format et de taille d'image (par exemple, un format 16:9 et une résolution 2K, ce qui donne une image de 2752x1536), comme suit :

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
);

// ...

Formats acceptés

Tous les modèles Gemini Nano Banana sont compatibles avec les formats suivants :

Par défaut : 1:1 (carré)

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

Tailles d'image (résolutions) compatibles

Les tailles d'image (résolutions) acceptées dépendent du modèle que vous utilisez.

Gemini Nano Banana modèle Tailles (résolutions) acceptées
Gemini Nano Banana 2.1
gemini-nano-banana-2.1
Par défaut : 1K (1024)
1K (1024), 2K (2048), 4K (4096)
Gemini Nano Banana 2
gemini-3.1-flash-image
Valeur par défaut : 1K (1024)
512, 1K (1024), 2K (2048), 4K (4096)
Gemini Nano Banana 2 Lite
gemini-3.1-flash-lite-image
Par défaut : 1K (1024)
512 (Gemini Developer API uniquement), 1K (1024)
Gemini Nano Banana Pro
gemini-3-pro-image
Par défaut : 1K (1024)
1K (1024), 2K (2048), 4K (4096)

Vous devez utiliser un suffixe K en majuscules (c'est-à-dire 1K, 2K, 4K). La valeur 512 n'utilise pas de suffixe K. Un suffixe k en minuscules (par exemple, 1k) sera refusé.

Notez que le modèle gemini-2.5-flash-image est fixé à 1K (1024).



Fonctionnalités compatibles

Voici les fonctionnalités compatibles, telles que les modalités, les outils, les entrées et les langues.

Pour connaître les formats et les résolutions compatibles avec chaque modèle, consultez Configurer la génération d'images plus haut dans ce guide.

Modalités compatibles

Voici les "modalités" compatibles avec les modèles Gemini Nano Banana. Ces "modalités" ne sont pas explicitement définies dans vos requêtes. Il s'agit plutôt de modèles recommandés pour les cas d'utilisation courants. Chaque modalité de cette liste présente un exemple de prompt et un exemple de code plus haut dans ce guide.

  • Texte Image(s) (texte uniquement vers image)

    • Génère une image de la tour Eiffel avec des feux d'artifice en arrière-plan.
  • Texte Image(s) (rendu du texte dans l'image)

    • Génère une photo cinématique d'un grand bâtiment avec ce texte géant projeté sur la façade.
  • Édition d'images (conversion de texte et d'image en image)

    • [image de scones] + Modifie cette image pour qu'elle ressemble à un dessin animé

    • [image d'un chat] + [image d'un coussin] + Crée un point de croix de mon chat sur ce coussin.

  • Vidéo et texte Image(s) (texte et vidéo vers image)

    • [vidéo/URL d'un parc] + Génère une image d'affiche qui capture les thèmes clés de cette vidéo.
  • Texte Image(s) et texte (entrelacés)

    • Génère une recette illustrée de paella. Créez des images en même temps que le texte lorsque vous générez la recette.

    • Génère une histoire sur un chien dans un style d'animation 3D. Pour chaque scène, générez une image.

  • Image(s) et texte Image(s) et texte (entrelacés)

    • [image d'une pièce meublée] + Quelles autres couleurs de canapé conviendraient à mon espace ? Peux-tu mettre à jour l'image ?
  • Modification d'images multitour (chat)

    • [image d'une voiture bleue] + Transforme cette voiture en cabriolet., puis Maintenant, change la couleur en jaune.

Outils compatibles

Compatibilité avec l'ancrage avec Google Search :

  • 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)

Autres fonctionnalités compatibles

  • Entrées multimodales acceptées :

    • Entrée d'image : tous les modèles Nano Banana.

    • Entrée vidéo :

      • 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)
    • Entrée audio : aucun des modèles Nano Banana.

  • Tous les modèles Nano Banana sont compatibles avec les éléments suivants :

    • Génération d'images PNG…
    • Générer et modifier des images de personnes.
    • Utiliser des filtres de sécurité qui offrent une expérience utilisateur flexible et moins restrictive.
  • Prise en charge de la génération de sorties structurées (comme JSON) :

    • Gemini Nano Banana Pro (gemini-3-pro-image)

Langues disponibles

Bien que les modèles Gemini Nano Banana puissent accepter des requêtes textuelles dans de nombreuses langues, les langues listées dans cette section vous offrent les meilleures performances.

Voici les langues acceptées pour le prompt textuel et le texte de l'image générée :

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

Pour utiliser une langue spécifique dans une image générée (même sans le code de langue), il vous suffit de le demander au modèle dans votre prompt (par exemple, "Mets à jour cette infographie pour qu'elle soit en espagnol. Ne modifie aucun autre élément de l'image.").

Notez que le modèle gemini-2.5-flash-image n'accepte que les langues EN, es-MX, ja-JP, zh-CN et hi-IN dans le prompt textuel et ne peut générer que de l'anglais dans les images.



Bonnes pratiques

Voici les bonnes pratiques pour les modèles Gemini Nano Banana.

  • Lorsque vous générez une image contenant du texte, générez d'abord le texte, puis générez une image avec ce texte.

  • La génération d'images peut ne pas toujours se déclencher. De plus, la génération d'images ou de texte peut ne pas fonctionner comme prévu dans les situations suivantes :

    • Le modèle peut ne générer que du texte et aucune image (en particulier si la requête est ambiguë). Dans ce cas, l'FinishReason a pour valeur NO_IMAGE.
      Essayez de demander explicitement des images en sortie. Par exemple, "générer une image", "fournir des images au fur et à mesure", "mettre à jour l'image".

    • Le modèle peut s'arrêter de générer des réponses en cours de route.
      Réessayez ou utilisez un autre prompt.

    • Le modèle peut générer du texte sous forme d'image.
      Essayez de demander explicitement des sorties textuelles. Par exemple, "générer un texte narratif avec des illustrations".

    • Si une requête est potentiellement dangereuse, il est possible que le modèle ne la traite pas et renvoie une réponse indiquant qu'il ne peut pas créer d'images dangereuses. Dans ce cas, l'FinishReason a pour valeur STOP.