Gemini Nano Banana का इस्तेमाल करके इमेज जनरेट करना और उनमें बदलाव करना


Gemini Nano Banana मॉडल से, इमेज जनरेट करने और उनमें बदलाव करने के लिए कहा जा सकता है. इसके लिए, सिर्फ़ टेक्स्ट वाले प्रॉम्प्ट और टेक्स्ट के साथ फ़ाइल वाले प्रॉम्प्ट, दोनों का इस्तेमाल किया जा सकता है. Firebase AI Logic का इस्तेमाल करने पर, सीधे अपने ऐप्लिकेशन से यह अनुरोध किया जा सकता है.

इस सुविधा की मदद से, ये काम किए जा सकते हैं:

  • नैचुरल लैंग्वेज का इस्तेमाल करके, बातचीत के ज़रिए बार-बार इमेज जनरेट करें. साथ ही, इमेज में बदलाव करते समय, एकरूपता और कॉन्टेक्स्ट का ध्यान रखें.

  • टेक्स्ट को अच्छी क्वालिटी में रेंडर करके इमेज जनरेट करना. इसमें टेक्स्ट की लंबी स्ट्रिंग भी शामिल हैं.

  • टेक्स्ट और इमेज के बेहतरीन सीक्वेंस वाला आउटपुट जनरेट करें. उदाहरण के लिए, एक ही बार में टेक्स्ट और इमेज वाली ब्लॉग पोस्ट. पहले, इसके लिए कई मॉडल को एक साथ जोड़ना पड़ता था.

  • Gemini की दुनिया भर की जानकारी और तर्क करने की क्षमताओं का इस्तेमाल करके इमेज जनरेट करें.

अपने अनुरोध के लिए, जवाब का मोड कॉन्फ़िगर किया जा सकता है, ताकि मॉडल सिर्फ़ इमेज या इमेज और टेक्स्ट, दोनों जनरेट करे. इस पेज पर आगे, इस्तेमाल की जा सकने वाली सुविधाओं की पूरी सूची और प्रॉम्प्ट के उदाहरण देखें.


टेक्स्ट से इमेज जनरेट करने के लिए कोड पर जाएं वीडियो से इमेज जनरेट करने के लिए कोड पर जाएं टेक्स्ट और इमेज को इंटरलीव करने के लिए कोड पर जाएं

इमेज में बदलाव करने के लिए कोड पर जाएं इमेज में बार-बार बदलाव करने के लिए कोड पर जाएं


इमेज के साथ काम करने के अन्य विकल्पों के बारे में जानने के लिए, अन्य गाइड देखें
इमेज का विश्लेषण करना उपयोगकर्ता के डिवाइस पर इमेज का विश्लेषण करना स्ट्रक्चर्ड आउटपुट जनरेट करना

शुरू करने से पहले

इस पेज पर, Gemini API की सेवा देने वाली कंपनी के हिसाब से कॉन्टेंट और कोड देखने के लिए, सेवा देने वाली कंपनी के नाम पर क्लिक करें.

अगर आपने अब तक ऐसा नहीं किया है, तो शुरुआती निर्देश पढ़ें. इसमें Firebase प्रोजेक्ट सेट अप करने, अपने ऐप्लिकेशन को Firebase से कनेक्ट करने, और SDK टूल जोड़ने का तरीका बताया गया है. साथ ही, इसमें अपनी पसंद के Gemini API प्रोवाइडर के लिए बैकएंड सेवा को शुरू करने और GenerativeModel इंस्टेंस बनाने का तरीका भी बताया गया है.

अपने प्रॉम्प्ट को टेस्ट करने और उनमें बदलाव करने के लिए, हमारा सुझाव है कि आप Google AI Studio का इस्तेमाल करें.

इस सुविधा के साथ काम करने वाले मॉडल

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

gemini-2.5-flash-image मॉडल में यह सुविधा काम करती है, लेकिन अब इसे बंद कर दिया गया है.

इमेज जनरेट करना और उनमें बदलाव करना

Gemini Nano Banana मॉडल का इस्तेमाल करके, इमेज जनरेट की जा सकती हैं और उनमें बदलाव किया जा सकता है.

इमेज जनरेट करना (सिर्फ़ टेक्स्ट इनपुट)

इस सैंपल को आज़माने से पहले, इस गाइड का शुरू करने से पहले सेक्शन पूरा करें. इससे आपको अपना प्रोजेक्ट और ऐप्लिकेशन सेट अप करने में मदद मिलेगी.
इस सेक्शन में, आपको सेवा देने वाली Gemini API कंपनी के लिए एक बटन पर भी क्लिक करना होगा, ताकि आपको इस पेज पर सेवा देने वाली कंपनी के हिसाब से कॉन्टेंट दिखे.

टेक्स्ट प्रॉम्प्ट देकर, Gemini Nano Banana मॉडल से इमेज जनरेट करने के लिए कहा जा सकता है.

GenerativeModel का इंस्टेंस बनाएं, अपने मॉडल कॉन्फ़िगरेशन में IMAGE के रिस्पॉन्स मोडैलिटी को शामिल करें, और 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
  }
}

इमेज में बदलाव करना (टेक्स्ट और इमेज इनपुट)

इस सैंपल को आज़माने से पहले, इस गाइड का शुरू करने से पहले सेक्शन पूरा करें, ताकि आप अपना प्रोजेक्ट और ऐप्लिकेशन सेट अप कर सकें.
इस सेक्शन में, आपको Gemini API सेवा देने वाली कंपनी के लिए एक बटन पर भी क्लिक करना होगा, ताकि आपको इस पेज पर सेवा देने वाली कंपनी के हिसाब से कॉन्टेंट दिखे.

Gemini Nano Banana मॉडल को इमेज में बदलाव करने के लिए कहा जा सकता है. इसके लिए, टेक्स्ट और एक या उससे ज़्यादा इमेज के साथ प्रॉम्प्ट दें.

GenerativeModel का इंस्टेंस बनाएं, अपने मॉडल कॉन्फ़िगरेशन में IMAGE के रिस्पॉन्स मोडैलिटी को शामिल करें, और 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
  }
}

वीडियो इनपुट (टेक्स्ट और वीडियो इनपुट) से इमेज जनरेट करना

इस सैंपल को आज़माने से पहले, इस गाइड का शुरू करने से पहले सेक्शन पूरा करें, ताकि आप अपना प्रोजेक्ट और ऐप्लिकेशन सेट अप कर सकें.
इस सेक्शन में, आपको Gemini APIसेवा देने वाली कंपनी के लिए एक बटन पर भी क्लिक करना होगा, ताकि आपको इस पेज पर सेवा देने वाली कंपनी के हिसाब से कॉन्टेंट दिखे.

Gemini Nano Banana मॉडल को टेक्स्ट और वीडियो प्रॉम्प्ट देकर, इमेज जनरेट करने के लिए कहा जा सकता है.

GenerativeModel का इंस्टेंस बनाएं, अपने मॉडल कॉन्फ़िगरेशन में IMAGE के रिस्पॉन्स मोडैलिटी को शामिल करें, और 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.
  }
}

इमेज और टेक्स्ट के बेहतरीन सीक्वेंस वाला आउटपुट जनरेट करें

इस सैंपल को आज़माने से पहले, इस गाइड का शुरू करने से पहले सेक्शन पूरा करें. इससे आपको अपना प्रोजेक्ट और ऐप्लिकेशन सेट अप करने में मदद मिलेगी.
इस सेक्शन में, आपको सेवा देने वाली Gemini API कंपनी के लिए एक बटन पर भी क्लिक करना होगा, ताकि आपको इस पेज पर सेवा देने वाली कंपनी के हिसाब से कॉन्टेंट दिखे.

Gemini Nano Banana मॉडल से, टेक्स्ट वाले जवाबों के साथ इमेज जनरेट करने के लिए कहा जा सकता है. उदाहरण के लिए, जनरेट की गई रेसिपी के हर चरण के निर्देशों के साथ-साथ, यह भी जनरेट किया जा सकता है कि हर चरण कैसा दिखेगा. इसके लिए, आपको मॉडल या अलग-अलग मॉडल से अलग-अलग अनुरोध करने की ज़रूरत नहीं है.

GenerativeModel इंस्टेंस बनाएं, अपने मॉडल कॉन्फ़िगरेशन में TEXT और IMAGE के रिस्पॉन्स मोड शामिल करें, और 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
      }
    }
  }
}

सिलसिलेवार बातचीत करके, इमेज में बदलाव करना

इस सैंपल को आज़माने से पहले, इस गाइड का शुरू करने से पहले सेक्शन पूरा करें. इससे आपको अपना प्रोजेक्ट और ऐप्लिकेशन सेट अप करने में मदद मिलेगी.
इस सेक्शन में, आपको सेवा देने वाली Gemini API कंपनी के लिए एक बटन पर भी क्लिक करना होगा, ताकि आपको इस पेज पर सेवा देने वाली कंपनी के हिसाब से कॉन्टेंट दिखे.

मल्टी-टर्न चैट का इस्तेमाल करके, Gemini Nano Banana मॉडल से जनरेट की गई इमेज या उसे दी गई इमेज में बदलाव किया जा सकता है.

GenerativeModel का इंस्टेंस बनाएं, अपने मॉडल कॉन्फ़िगरेशन में IMAGE के रिस्पॉन्स मोडैलिटी को शामिल करें, और नए उपयोगकर्ता मैसेज भेजने के लिए, startChat() और sendMessage() को कॉल करें.

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
}



रेफ़रंस के लिए इमेज उपलब्ध कराना

Gemini Nano Banana मॉडल की मदद से, अपने प्रॉम्प्ट में रेफ़रंस इमेज जोड़ी जा सकती हैं. इन इमेज में ये शामिल हो सकते हैं:

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

    • फ़ाइनल इमेज में शामिल करने के लिए, हाई फ़िडेलिटी वाले ऑब्जेक्ट की ज़्यादा से ज़्यादा 10 इमेज
    • किरदार का लुक बरकरार रखने के लिए, ज़्यादा से ज़्यादा चार इमेज
  • Gemini Nano Banana 2 (gemini-3.1-flash-image):

    • फ़ाइनल इमेज में शामिल करने के लिए, हाई फ़िडेलिटी वाले ऑब्जेक्ट की ज़्यादा से ज़्यादा 10 इमेज
    • किरदार का लुक बरकरार रखने के लिए, ज़्यादा से ज़्यादा चार इमेज
  • Gemini Nano Banana 2 Lite (gemini-3.1-flash-lite-image):

    • फ़ाइनल इमेज में शामिल करने के लिए, हाई फ़िडेलिटी वाले ऑब्जेक्ट की ज़्यादा से ज़्यादा 10 इमेज
    • कैरेक्टर का लुक बरकरार रखने के लिए, ज़्यादा से ज़्यादा चार इमेज
  • Gemini Nano Banana Pro (gemini-3-pro-image)

    • फ़ाइनल इमेज में शामिल करने के लिए, हाई-फ़िडेलिटी वाले ऑब्जेक्ट की ज़्यादा से ज़्यादा छह इमेज
    • किरदार का लुक बरकरार रखने के लिए, किरदार की ज़्यादा से ज़्यादा पांच इमेज
    • स्टाइल के रेफ़रंस के तौर पर इस्तेमाल करने के लिए, ज़्यादा से ज़्यादा तीन इमेज

ध्यान दें कि gemini-2.5-flash-image मॉडल में सिर्फ़ तीन इमेज इस्तेमाल की जा सकती हैं.

इमेज जनरेट करने की सुविधा को कॉन्फ़िगर करना

डिफ़ॉल्ट रूप से, Gemini Nano Banana मॉडल 1024x1024 रिज़ॉल्यूशन में स्क्वेयर इमेज (1:1 आसपेक्ट रेशियो) जनरेट करते हैं. generationConfig में मौजूद imageConfig प्रॉपर्टी का इस्तेमाल करके, जनरेटिव इमेज के आउटपुट को पसंद के मुताबिक बनाया जा सकता है.

उदाहरण के लिए, आउटपुट इमेज को कॉन्फ़िगर करने के लिए, आसपेक्ट रेशियो (लंबाई-चौड़ाई का अनुपात) और इमेज के साइज़ के एनम का इस्तेमाल किया जा सकता है. जैसे, 16:9 आसपेक्ट रेशियो और 2K रिज़ॉल्यूशन, जिससे 2752x1536 इमेज बनती है. इसके लिए, यह तरीका अपनाएं:

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

// ...

काम करने वाले आसपेक्ट रेशियो (लंबाई-चौड़ाई का अनुपात)

Gemini Nano Banana के सभी मॉडल, इन आसपेक्ट रेशियो (लंबाई-चौड़ाई का अनुपात) के साथ काम करते हैं:

डिफ़ॉल्ट: 1:1 (स्क्वेयर)

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

इमेज के साइज़ (रिज़ॉल्यूशन)

इमेज के साइज़ (रिज़ॉल्यूशन), इस्तेमाल किए जा रहे मॉडल पर निर्भर करते हैं.

Gemini Nano Banana मॉडल इस्तेमाल किए जा सकने वाले साइज़ (रिज़ॉल्यूशन)
Gemini Nano Banana 2.1
gemini-nano-banana-2.1
डिफ़ॉल्ट: 1K (1024)
1K (1024), 2K (2048), 4K (4096)
Gemini Nano Banana 2
gemini-3.1-flash-image
डिफ़ॉल्ट: 1K (1024)
512, 1K (1024), 2K (2048), 4K (4096)
Gemini Nano Banana 2 Lite
gemini-3.1-flash-lite-image
डिफ़ॉल्ट: 1K (1024)
512 (सिर्फ़ Gemini Developer API), 1K (1024)
Gemini Nano Banana Pro
gemini-3-pro-image
डिफ़ॉल्ट: 1K (1024)
1K (1024), 2K (2048), 4K (4096)

आपको अंग्रेज़ी के बड़े अक्षरों में K सफ़िक्स का इस्तेमाल करना होगा. जैसे, 1K, 2K, 4K. 512 वैल्यू में K सफ़िक्स का इस्तेमाल नहीं किया जाता. लोअरकेस में k सफ़िक्स (उदाहरण के लिए, 1k) को अस्वीकार कर दिया जाएगा.

ध्यान दें कि gemini-2.5-flash-image मॉडल, 1K (1024) पर सेट है.



इस्तेमाल की जा सकने वाली सुविधाएं

यहां उन सुविधाओं के बारे में बताया गया है जो Gemini API के साथ काम करती हैं. जैसे, मोडैलिटी, टूल, इनपुट, और भाषाएं.

हर मॉडल के लिए, काम करने वाले आसपेक्ट रेशियो (लंबाई-चौड़ाई का अनुपात) और रिज़ॉल्यूशन के बारे में जानने के लिए, इस गाइड में पहले मौजूद इमेज जनरेशन को कॉन्फ़िगर करना सेक्शन देखें.

इस्तेमाल किए जा सकने वाले मोड

Gemini Nano Banana मॉडल के लिए, ये "मोडैलिटी" इस्तेमाल की जा सकती हैं. ये "मोडैलिटी" आपके अनुरोधों में साफ़ तौर पर सेट नहीं की जाती हैं. ये आम तौर पर इस्तेमाल होने वाले मामलों के लिए, सुझाए गए पैटर्न की तरह होते हैं. इस सूची में मौजूद हर मोड के लिए, एक प्रॉम्प्ट का उदाहरण दिया गया है. साथ ही, इस गाइड में पहले एक कोड सैंपल भी दिया गया है.

  • टेक्स्ट इमेज (सिर्फ़ टेक्स्ट से इमेज जनरेट करना)

    • आइफ़िल टावर की एक इमेज जनरेट करो, जिसके बैकग्राउंड में पटाखे फूट रहे हों.
  • टेक्स्ट इमेज (इमेज में टेक्स्ट रेंडर करना)

    • एक बड़ी इमारत की सिनमैटिक फ़ोटो जनरेट करो. इसमें इमारत के सामने वाले हिस्से पर, बड़े साइज़ में टेक्स्ट का प्रोजेक्शन मैप किया गया हो.
  • इमेज में बदलाव करना (टेक्स्ट और इमेज से इमेज जनरेट करना)

    • [स्कॉन की इमेज] + इस इमेज में बदलाव करके इसे कार्टून जैसा बनाओ

    • [बिल्ली की इमेज] + [तकिए की इमेज] + इस तकिए पर मेरी बिल्ली की क्रॉस स्टिच वाली इमेज बनाओ.

  • वीडियो और टेक्स्ट इमेज (टेक्स्ट और वीडियो से इमेज जनरेट करना)

    • [video/URL of a park] + Generate a poster image that captures the key themes of this video.
  • टेक्स्ट इमेज और टेक्स्ट (इंटरलीव्ड)

    • पाएला बनाने की रेसिपी के लिए इलस्ट्रेशन जनरेट करो. रेसिपी जनरेट करते समय, टेक्स्ट के साथ-साथ इमेज भी बनाएं.

    • 3D कार्टून एनिमेशन स्टाइल में, किसी कुत्ते के बारे में एक कहानी जनरेट करो. हर सीन के लिए एक इमेज जनरेट करें.

  • इमेज और टेक्स्ट इमेज और टेक्स्ट (इंटरलीव्ड)

    • [फ़र्नीचर से सजे कमरे की इमेज] + मेरे कमरे में और किस रंग के सोफ़े अच्छे लगेंगे? क्या इमेज को अपडेट किया जा सकता है?
  • इमेज में कई बार बदलाव करने की सुविधा (चैट)

    • [नीली कार की इमेज] + इस कार को कन्वर्टिबल कार में बदलो. इसके बाद, अब इसका रंग बदलकर पीला कर दो.

इस्तेमाल किए जा सकने वाले टूल

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)

इस्तेमाल की जा सकने वाली अन्य सुविधाएं

  • मल्टीमोडल इनपुट के लिए इस्तेमाल किए जा सकने वाले फ़ॉर्मैट:

    • इमेज इनपुट: Nano Banana के सभी मॉडल.

    • वीडियो इनपुट:

      • 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)
    • ऑडियो इनपुट: Nano Banana मॉडल में से कोई भी नहीं.

  • Nano Banana के सभी मॉडल में ये सुविधाएं काम करती हैं:

    • PNG इमेज जनरेट की जा रही हैं.
    • लोगों की इमेज जनरेट करना और उनमें बदलाव करना.
    • सुरक्षा फ़िल्टर का इस्तेमाल करना, ताकि उपयोगकर्ताओं को ज़रूरत के हिसाब से और कम पाबंदियों वाला अनुभव मिले.
  • JSON जैसे स्ट्रक्चर्ड आउटपुट जनरेट करने की सुविधा:

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

यह सुविधा इन भाषाओं में काम करती है

Gemini Nano Banana मॉडल, कई भाषाओं में टेक्स्ट प्रॉम्प्ट स्वीकार कर सकते हैं. हालांकि, इस सेक्शन में दी गई भाषाओं में आपको सबसे अच्छी परफ़ॉर्मेंस मिलेगी.

टेक्स्ट प्रॉम्प्ट और जनरेट की गई इमेज में मौजूद टेक्स्ट के लिए, इन भाषाओं का इस्तेमाल किया जा सकता है:

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

जनरेट की गई इमेज में किसी खास भाषा का इस्तेमाल करने के लिए (भाषा के कोड के बिना भी), अपने प्रॉम्प्ट में मॉडल से कहें. उदाहरण के लिए, "इस इन्फ़ोग्राफ़िक को स्पैनिश में अपडेट करो. इमेज के किसी अन्य एलिमेंट में बदलाव न करें.").

ध्यान दें कि gemini-2.5-flash-image मॉडल, टेक्स्ट प्रॉम्प्ट में सिर्फ़ EN, es-MX, ja-JP, zh-CN, hi-IN को सपोर्ट करता है. साथ ही, यह इमेज में सिर्फ़ अंग्रेज़ी टेक्स्ट जनरेट कर सकता है.



सबसे सही तरीके

Gemini Nano Banana मॉडल के लिए, यहां सबसे सही तरीके दिए गए हैं.

  • टेक्स्ट वाली इमेज जनरेट करते समय, पहले टेक्स्ट जनरेट करें. इसके बाद, उस टेक्स्ट के साथ इमेज जनरेट करें.

  • ऐसा हो सकता है कि इमेज जनरेट करने की सुविधा हमेशा ट्रिगर न हो. इसके अलावा, ऐसा हो सकता है कि इन स्थितियों में इमेज या टेक्स्ट जनरेट करने की सुविधा उम्मीद के मुताबिक काम न करे:

    • ऐसा हो सकता है कि मॉडल सिर्फ़ टेक्स्ट जनरेट करे और कोई इमेज जनरेट न करे. ऐसा खास तौर पर तब होता है, जब प्रॉम्प्ट साफ़ तौर पर न दिया गया हो. अगर ऐसा होता है, तो FinishReason NO_IMAGE है.
      Gemini से साफ़ तौर पर इमेज जनरेट करने के लिए कहें. उदाहरण के लिए, "इमेज जनरेट करो", "जवाब के साथ इमेज भी दिखाओ", "इमेज अपडेट करो".

    • ऐसा हो सकता है कि मॉडल, जवाब जनरेट करने की प्रोसेस को बीच में ही रोक दे.
      फिर से कोशिश करें या कोई दूसरा प्रॉम्प्ट आज़माएं.

    • मॉडल, टेक्स्ट को इमेज के तौर पर जनरेट कर सकता है.
      साफ़ तौर पर टेक्स्ट आउटपुट देने के लिए कहें. उदाहरण के लिए, "इलस्ट्रेशन के साथ नैरेटिव टेक्स्ट जनरेट करो".

    • अगर कोई प्रॉम्प्ट असुरक्षित हो सकता है, तो हो सकता है कि मॉडल उस अनुरोध को प्रोसेस न करे. इसके बजाय, वह जवाब दे कि असुरक्षित इमेज जनरेट नहीं की जा सकतीं. अगर ऐसा होता है, तो FinishReason STOP है.