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 모델에 텍스트 대답과 함께 인터리브 처리된 이미지를 생성하도록 요청할 수 있습니다. 예를 들어 모델 또는 다른 모델에 별도의 요청을 하지 않고도 생성된 레시피의 각 단계가 어떻게 표시되는지 AI 생성 이미지를 생성하여 해당 단계의 안내와 함께 표시할 수 있습니다.

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개
    • 캐릭터 일관성을 유지하기 위한 캐릭터 이미지 최대 4개
  • Gemini Nano Banana 2 (gemini-3.1-flash-image):

    • 최종 이미지에 포함할 충실도 높은 객체 이미지 최대 10개
    • 캐릭터 일관성을 유지하기 위한 캐릭터 이미지 최대 4개
  • Gemini Nano Banana 2 Lite (gemini-3.1-flash-lite-image):

    • 최종 이미지에 포함할 충실도 높은 객체 이미지 최대 10개
    • 캐릭터 일관성을 유지하기 위한 캐릭터 이미지 최대 4개
  • Gemini Nano Banana Pro회(gemini-3-pro-image)

    • 최종 이미지에 포함할 충실도 높은 객체 이미지 최대 6개
    • 캐릭터 일관성을 유지하기 위한 캐릭터 이미지 최대 5개
    • 스타일 참조로 사용할 이미지 최대 3개

gemini-2.5-flash-image 모델은 이미지를 최대 3개까지만 지원합니다.

이미지 생성 구성

기본적으로 Gemini Nano Banana 모델은 1024x1024 해상도로 정사각형 이미지(가로세로 비율 1:1)를 생성합니다. generationConfig 내의 imageConfig 속성을 사용하여 생성된 이미지의 출력을 맞춤설정할 수 있습니다.

예를 들어 가로세로 비율과 이미지 크기 enum (예: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 Nano Banana 모델에 지원되는 '모달리티'입니다. 이러한 '모달리티'는 요청에 명시적으로 설정되지 않습니다. 일반적인 사용 사례에 권장되는 패턴에 가깝습니다. 이 목록의 각 형식은 프롬프트 예시를 보여주며 이 가이드의 앞부분에 코드 샘플 예시가 있습니다.

  • 텍스트 이미지(텍스트만 이미지로 변환)

    • 배경에 불꽃놀이가 있는 에펠탑 이미지를 생성해 줘.
  • 텍스트 이미지(이미지 내 텍스트 렌더링)

    • 대형 건물의 영화 모션 효과 사진을 생성해 줘. 건물 전면에 거대한 텍스트 프로젝션이 매핑되어 있어.
  • 이미지 편집 (텍스트 및 이미지 간)

    • [스콘 이미지] + 이 이미지를 만화처럼 보이도록 수정해 줘

    • [고양이 이미지] + [베개 이미지] + 이 베개에 내 고양이 십자수를 만들어 줘.

  • 동영상 및 텍스트 이미지(텍스트 및 동영상에서 이미지로)

    • [공원 동영상/URL] + 이 동영상의 주요 주제를 담은 포스터 이미지를 생성해 줘.
  • 텍스트 이미지 및 텍스트(인터리브 처리)

    • 파에야에 관한 그림이 있는 레시피를 생성해 줘. 레시피를 생성할 때 텍스트와 함께 이미지를 만들어 줘.

    • 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

AI 생성 이미지 내에서 특정 언어를 사용하려면 (언어 코드 없이도) 프롬프트 내에서 모델에 요청하면 됩니다 (예: '이 인포그래픽을 스페인어로 업데이트해 줘. 이미지의 다른 요소는 변경하지 마세요.").

gemini-2.5-flash-image 모델은 텍스트 프롬프트에서 EN, es-MX, ja-JP, zh-CN, hi-IN만 지원하며 이미지에서 영어만 생성할 수 있습니다.



권장사항

다음은 Gemini Nano Banana 모델의 권장사항입니다.

  • 텍스트가 포함된 이미지를 생성할 때는 먼저 텍스트를 생성한 다음 해당 텍스트가 포함된 이미지를 생성합니다.

  • 이미지 생성이 항상 트리거되지는 않을 수 있습니다. 또한 다음과 같은 상황에서는 이미지 또는 텍스트 생성이 예상대로 작동하지 않을 수 있습니다.

    • 모델은 텍스트만 생성하고 이미지는 생성하지 않을 수 있습니다 (특히 프롬프트가 모호한 경우). 이 경우 FinishReason는 NO_IMAGE입니다.
      이미지 출력을 명시적으로 요청해 보세요. 예를 들어 '이미지 생성', '진행하면서 이미지 제공', '이미지 업데이트' 등이 있습니다.

    • 모델이 생성을 중단할 수 있습니다.
      다시 시도하거나 다른 프롬프트를 사용해 보세요.

    • 모델은 텍스트를 이미지로 생성할 수 있습니다.
      텍스트 출력을 명시적으로 요청해 보세요. 예를 들어 '삽화와 함께 서술 텍스트를 생성해 줘.'

    • 프롬프트가 안전하지 않을 수 있는 경우 모델은 요청을 처리하지 않고 대신 안전하지 않은 이미지를 만들 수 없다는 응답을 반환할 수 있습니다. 이 경우 FinishReason는 STOP입니다.