ย้ายข้อมูลจาก Imagen ไปยังโมเดล Gemini Nano Banana


โมเดล Imagen ทั้งหมดจะเลิกใช้งานและจะปิดตัวลงตั้งแต่วันที่ 17 สิงหาคม 2026 การเลิกใช้งานและการปิดระบบนี้มีผลกับ Google ทั้งหมด รวมถึงทั้ง Gemini Developer API และ Agent Platform Gemini API (formerly Vertex AI)

ก่อนวันที่ปิดให้บริการนี้ คุณควรย้ายข้อมูลแอปจากการใช้โมเดล Imagen ไปใช้โมเดล Gemini Nano Banana ตามที่อธิบายไว้ในคู่มือนี้เพื่อหลีกเลี่ยงไม่ให้บริการหยุดชะงัก

หากคุณมีปัญหาเร่งด่วนเกี่ยวกับการเลิกใช้งานและการปิดระบบนี้ โปรดติดต่อทีมสนับสนุนของ Firebase

โมเดล Nano Banana ที่ใช้แทน

ตารางต่อไปนี้จะช่วยคุณเลือกโมเดล Nano Banana ที่จะใช้แทนสำหรับแอปของคุณ

รุ่น Imagen รุ่น Gemini Nano Banana
imagen-4.0-fast-generate-001 gemini-nano-banana-2.1 (ที่มีระดับการคิด MINIMAL)
imagen-4.0-generate-001 gemini-nano-banana-2.1 (ที่มีระดับการคิด HIGH)
imagen-4.0-ultra-generate-001 gemini-3-pro-image
imagen-3.0-capability-001 gemini-nano-banana-2.1

ย้ายข้อมูลแอปของคุณ

ส่วนนี้แสดงตัวอย่างก่อนและหลังการย้ายข้อมูลจากโมเดล Imagen ไปยังโมเดล Gemini Nano Banana

สร้างรูปภาพจากข้อความ

คลิกผู้ให้บริการ Gemini API เพื่อดูเนื้อหาและโค้ดเฉพาะของผู้ให้บริการในหน้านี้

หากต้องการสร้างรูปภาพจากข้อความ ให้ย้ายข้อมูลแอปโดยทำการเปลี่ยนแปลงต่อไปนี้

  • ใช้โมเดล Nano Banana ทดแทนที่เหมาะสม (เช่น gemini-nano-banana-2.1)

  • สร้างอินสแตนซ์ GenerativeModel (แทนอินสแตนซ์ ImagenModel)

  • อัปเดตตัวเลือกการกำหนดค่าโมเดลเพื่อรองรับโมเดล Nano Banana

    • ในการกำหนดค่านี้ ให้ตั้งค่ารูปแบบการตอบกลับเป็น IMAGE
      โปรดทราบว่าโมเดล Nano Banana สามารถกำหนดค่าให้แสดงผลทั้งรูปภาพและข้อความได้

Swift

ก่อน


import FirebaseAILogic

// Initialize the Gemini Developer API backend service.
let ai = FirebaseAI.firebaseAI(backend: .googleAI())

// Create an `ImagenModel` instance with a model that supports your use case.
let model = ai.imagenModel(modelName: "IMAGEN_MODEL_NAME")

// Provide an image generation prompt.
let prompt = "An astronaut riding a horse"

// To generate an image, call `generateImages` with the text prompt.
let response = try await model.generateImages(prompt: prompt)

// Handle the generated image.
guard let image = response.images.first else {
  fatalError("No image in the response.")
}
let uiImage = UIImage(data: image.data)

หลัง


import FirebaseAILogic

// Initialize the Gemini Developer API backend service.
let ai = FirebaseAI.firebaseAI(backend: .googleAI())

// Create a `GenerativeModel` instance with a Gemini model that supports image output.
let model = ai.generativeModel(
  modelName: "GEMINI_NANOBANANA_MODEL_NAME",
  generationConfig: GenerationConfig(
    responseModalities: [.image],
    imageConfig: ImageConfig(aspectRatio: .landscape4x3)
  )
)

// Provide an image generation prompt.
let prompt = "An astronaut riding a horse"

// To generate an image, call `generateContent` with the text prompt.
let response = try await model.generateContent(prompt)

// Handle the case where no images were generated.
guard let inlineDataPart = response.inlineDataParts.first else {
  fatalError("No image in the response.")
}

// Process the image.
guard let uiImage = UIImage(data: inlineDataPart.data) else {
  fatalError("Failed to convert data to UIImage.")
}

Kotlin

ก่อน


// Initialize the Gemini Developer API backend service.
val ai = Firebase.ai(backend = GenerativeBackend.googleAI())

// Create an `ImagenModel` instance with an Imagen model that supports your use case.
val model = ai.imagenModel("IMAGEN_MODEL_NAME")

// Provide an image generation prompt.
val prompt = "An astronaut riding a horse"

// To generate an image, call `generateImages` with the text prompt.
val imageResponse = model.generateImages(prompt)

// Handle the generated image.
val image = imageResponse.images.first()

val bitmapImage = image.asBitmap()

หลัง


// Initialize the Gemini Developer API backend service.
val ai = Firebase.ai(backend = GenerativeBackend.googleAI())

// Create a `GenerativeModel` instance with a Gemini model that supports image output.
val model = ai.generativeModel(
    modelName = "GEMINI_NANOBANANA_MODEL_NAME",
    generationConfig = generationConfig {
      responseModalities = listOf(ResponseModality.IMAGE),
      imageConfig = imageConfig {
        aspectRatio = AspectRatio.LANDSCAPE_4x3
      }
    }
)

// Provide an image generation prompt.
val prompt = "An astronaut riding a horse"

// To generate an image, call `generateContent` with the text prompt.
val imageResponse = model.generateContent(prompt)

if (imageResponse.finishReason == FinishReason.NO_IMAGE) {
  // Handle the case where no images were generated.
} else {
  // Handle the generated image.
  val bitmapImage = imageResponse.candidates.first().content.parts.filterIsInstance().firstOrNull()?.image
}

Java

ก่อน


// Initialize the Gemini Developer API backend service.
// Create an `ImagenModel` instance with an Imagen model that supports your use case.
ImagenModel imagenModel = FirebaseAI.getInstance(GenerativeBackend.googleAI())
        .imagenModel(
                /* modelName */ "IMAGEN_MODEL_NAME");

ImagenModelFutures model = ImagenModelFutures.from(imagenModel);

// Provide an image generation prompt.
String prompt = "An astronaut riding a horse";

// To generate an image, call `generateImages` with the text prompt.
Futures.addCallback(model.generateImages(prompt), new FutureCallback<ImagenGenerationResponse>() {
    @Override
    public void onSuccess(ImagenGenerationResponse result) {
        if (result.getImages().isEmpty()) {
            Log.d("TAG", "No images generated");
        }
        Bitmap bitmap = result.getImages().get(0).asBitmap();
        // Use the bitmap to display the image in your UI.
    }

    @Override
    public void onFailure(Throwable t) {
        // ...
    }
}, Executors.newSingleThreadExecutor());

หลัง


// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI()).generativeModel(
    "GEMINI_NANOBANANA_MODEL_NAME",
    new GenerationConfig.Builder()
        .setResponseModalities(Arrays.asList(ResponseModality.IMAGE))
        .setImageConfig(new ImageConfig(AspectRatio.LANDSCAPE_4x3, null))
        .build()
);

GenerativeModelFutures model = GenerativeModelFutures.from(ai);

// Provide a text prompt instructing the model to generate an image.
Content prompt = new Content.Builder()
        .addText("An astronaut riding a horse")
        .build();

// To generate an image, call `generateContent` with the text input.
Executor executor = Executors.newSingleThreadExecutor();
ListenableFuture response = model.generateContent(prompt);
Futures.addCallback(response, new FutureCallback() {
    @Override
    public void onSuccess(GenerateContentResponse result) {
        if (result.finishReason == FinishReason.NO_IMAGE) {
            // handle the case where no images were generated
            return;
        }
        // iterate over all the parts in the first candidate in the result object.
        for (Part part : result.getCandidates().get(0).getContent().getParts()) {
            if (part instanceof ImagePart) {
                ImagePart imagePart = (ImagePart) part;
                // The returned image as a bitmap
                Bitmap generatedImageAsBitmap = imagePart.getImage();
                break;
            }
        }
    }

    @Override
    public void onFailure(Throwable t) {
        t.printStackTrace();
    }
}, executor);

Web

ก่อน


import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, getImagenModel, GoogleAIBackend } from "firebase/ai";

// TODO(developer): Replace the following with your app's Firebase configuration
const firebaseConfig = {
  // ...
};

// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);

// Initialize the Gemini Developer API backend service.
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

// Create an `ImagenModel` instance with an Imagen model that supports your use case.
const model = getImagenModel(ai, { model: "IMAGEN_MODEL_NAME" });

// Provide an image generation prompt.
const prompt = "An astronaut riding a horse.";

// To generate an image, call `generateImages` with the text prompt.
const response = await model.generateImages(prompt)

// If fewer images were generated than were requested,
// then `filteredReason` will describe the reason they were filtered out.
if (response.filteredReason) {
  console.log(response.filteredReason);
}

if (response.images.length == 0) {
  throw new Error("No images in the response.")
}

const image = response.images[0];

หลัง


import { initializeApp } from "firebase/app";
import {
  getAI,
  getGenerativeModel,
  GoogleAIBackend,
  ResponseModality,
  ImageConfigAspectRatio,
  FinishReason
} from "firebase/ai";

// TODO(developer): Replace the following with your app's Firebase configuration
const firebaseConfig = {
  // ...
};

// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);

// Initialize the Gemini Developer API backend service.
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

// Create a `GenerativeModel` instance with a model that supports your use case.
const model = getGenerativeModel(ai, {
  model: "GEMINI_NANOBANANA_MODEL_NAME",
  generationConfig: {
    responseModalities: [ResponseModality.IMAGE],
    imageConfig: {
      aspectRatio: ImageConfigAspectRatio.LANDSCAPE_4x3
    }
  },
});

// Provide an image generation prompt.
const prompt = "An astronaut riding a horse.";

// To generate an image, call `generateContent` with the text prompt.
const result = await model.generateContent(prompt);

// Handle the generated image.
try {
  const response = result.response;
  if (response.candidates?.[0].finishReason == FinishReason.NO_IMAGE) {
    // Handle the case where no images were generated.
  }
  const inlineDataParts = response.inlineDataParts();
  if (inlineDataParts?.[0]) {
    const image = inlineDataParts[0].inlineData;
    // Use this mimeType and base64 data to display the image using your preferred tooling.
    console.log(image.mimeType, image.data);
  }
} catch (err) {
  console.error('Prompt or candidate was blocked:', err);
}

Dart

ก่อน


import 'package:firebase_ai/firebase_ai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';

// Initialize FirebaseApp
await Firebase.initializeApp(
  options: DefaultFirebaseOptions.currentPlatform,
);

// Initialize the Gemini Developer API backend service.
final ai = FirebaseAI.googleAI();

// Create an `ImagenModel` instance with an Imagen model that supports your use case.
final model = ai.imagenModel(model: 'IMAGEN_MODEL_NAME');

// Provide an image generation prompt.
const prompt = 'An astronaut riding a horse.';

// To generate an image, call `generateImages` with the text prompt.
final response = await model.generateImages(prompt);

if (response.images.isNotEmpty) {
  final image = response.images[0];
  // Process the image.
} else {
  // Handle the case where no images were generated.
  print('Error: No images were generated.');
}

หลัง


import 'package:firebase_ai/firebase_ai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';

// Initialize FirebaseApp
await Firebase.initializeApp(
  options: DefaultFirebaseOptions.currentPlatform,
);

// Initialize the Gemini Developer API backend service.
final ai = FirebaseAI.googleAI();

// Create a `GenerativeModel` instance with a Gemini model that supports image output.
final model = ai.generativeModel(
  model: 'GEMINI_NANOBANANA_MODEL_NAME',
  generationConfig: GenerationConfig(
    responseModalities: [ResponseModalities.image],
    imageConfig: ImageConfig(aspectRatio: ImageAspectRatio.landscape4x3)
  ),
);

// Provide a text prompt instructing the model to generate an image.
final prompt = [Content.text('An astronaut riding a horse.')];

// To generate an image, call `generateContent` with the text prompt.
final response = await model.generateContent(prompt);
if (response.inlineDataParts.isNotEmpty) {
  final imageBytes = response.inlineDataParts.first.bytes;
  // Process the image.
} else {
  // Handle the case where no images were generated.
  print('Error: No images were generated.');
}

Unity

ก่อน


using Firebase.AI;

// Initialize the Gemini Developer API backend service
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());

// Create an `ImagenModel` instance with a model that supports your use case
var model = ai.GetImagenModel(modelName: "IMAGEN_MODEL_NAME");

// Provide an image generation prompt
var prompt = "An astronaut riding a horse";

// To generate an image, call `generateImages` with the text prompt
var response = await model.GenerateImagesAsync(prompt: prompt);

// Handle the generated image
if (response.Images.Count == 0) {
  throw new Exception("No image in the response.");
}
var image = response.Images[0].AsTexture2D();

หลัง


using Firebase;
using Firebase.AI;

// Initialize the Gemini Developer API backend service.
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());

// Create a `GenerativeModel` instance with a Gemini model that supports image output.
var model = ai.GetGenerativeModel(
  modelName: "GEMINI_NANOBANANA_MODEL_NAME",
  generationConfig: new GenerationConfig(
    responseModalities: new[] { ResponseModality.Image },
    imageConfig: new ImageConfig(aspectRatio: ImageConfig.AspectRatio.Landscape4x3)
  )
);

// Provide an image generation prompt.
var prompt = "An astronaut riding a horse";

// To generate an image, call `GenerateContentAsync` with the text prompt.
var response = await model.GenerateContentAsync(prompt);

if (response.Candidates.First().FinishReason == FinishReason.NoImage) {
  // Handle the case where no images were generated.
}

// Handle the generated image.
var imageParts = response.Candidates.First().Content.Parts
                         .OfType<ModelContent.InlineDataPart>()
                         .Where(part => part.MimeType == "image/png");

foreach (var imagePart in imageParts) {
  // Load the Image into a Unity Texture2D object.
  UnityEngine.Texture2D texture2D = new(2, 2);
  if (texture2D.LoadImage(imagePart.Data.ToArray())) {
    // Do something with the image.
  }
}

ตัวเลือกการกำหนดค่าการเปลี่ยนทดแทน

ส่วนนี้จะอธิบายตัวเลือกการแทนที่สำหรับตัวเลือกการกำหนดค่าโมเดลต่างๆ เพื่อช่วยควบคุมการตอบสนองของโมเดล

การตั้งค่าความปลอดภัย

คุณกำหนดการตั้งค่าความปลอดภัยสำหรับโมเดล Imagen โดยใช้ ImagenSafetySettings อย่างไรก็ตาม สำหรับโมเดล Nano Banana คุณต้องย้ายข้อมูลไปใช้ SafetySetting

พารามิเตอร์การกำหนดค่าโมเดล

คุณกำหนดค่าโมเดล Imagen ด้วย ImagenGenerationConfig อย่างไรก็ตาม สำหรับโมเดล Nano Banana คุณต้องย้ายข้อมูลไปใช้ GenerationConfig และ ImageConfig ที่ฝังอยู่ (ไม่บังคับ) (พร้อมใช้งานตั้งแต่ SDK เวอร์ชันต้นเดือนพฤษภาคม 2026 เป็นต้นไป)

ในฐานะส่วนหนึ่งของ GenerationConfig ให้ตั้งค่ารูปแบบการตอบกลับเป็น IMAGE (ตามที่แสดงในตัวอย่างโค้ด "หลัง" ก่อนหน้านี้ในคู่มือนี้) โปรดทราบว่าคุณสามารถเลือกกำหนดค่าโมเดล Nano Banana ให้แสดงทั้งIMAGE และ TEXTได้

ตารางต่อไปนี้จะช่วยให้คุณเข้าใจวิธีย้ายข้อมูลพารามิเตอร์การกำหนดค่าโมเดลจากโมเดล Imagen ไปยังโมเดล Nano Banana

รุ่น Imagen รุ่น Gemini Nano Banana
addWatermark

ไม่รองรับ

โมเดล Nano Banana จะแสดงรูปภาพจาก Generative AI ที่สร้างขึ้นพร้อมลายน้ำ SynthID เสมอ

aspectRatio

ใช้ aspectRatio ใน ImageConfig

ดูตัวอย่างโค้ดและค่าที่รองรับได้ที่หัวข้อกำหนดค่าการสร้างรูปภาพในคู่มือโมเดล Nano Banana

imageFormat

ไม่รองรับ

โมเดล Nano Banana จะแสดงรูปภาพที่สร้างขึ้นในรูปแบบ PNG เสมอ

negativePrompt

ไม่รองรับ

โปรดทราบว่าพรอมต์เชิงลบเป็นฟีเจอร์เก่า และไม่ได้รับการรองรับตั้งแต่ imagen-3.0-generate-002 (หรือโดยโมเดล Imagen 4 ใดๆ)

numberOfImages

ไม่รองรับ

โมเดล Nano Banana จะแสดงผลรูปภาพที่สร้างขึ้นเพียงรูปเดียวเสมอ
วิธีแก้ปัญหาคือ คุณสามารถเรียกใช้การสร้างแบบวนซ้ำเพื่อให้ได้ผลลัพธ์เดียวกัน โปรดทราบว่าจำนวนผู้สมัครไม่สามารถใช้แทนได้

personGeneration

ไม่รองรับ

โดยค่าเริ่มต้น โมเดล Nano Banana จะอนุญาตให้สร้างรูปภาพผู้คน