从 Imagen 迁移到 Gemini 图片模型(“Nano Banana”)


所有 Imagen 模型均已弃用,最早将于 2026 年 8 月 17 日关停。此弃用和关停适用于整个 Google,并且适用于 Gemini Developer APIAgent Platform Gemini API (formerly Vertex AI)

为避免服务中断,您应在此关停日期之前,按照本指南中的说明将应用从使用 Imagen 模型迁移到使用 Gemini 3.x Image 模型(“Nano Banana”模型)。

如果您遇到与此弃用和关闭相关的紧急问题,请与 Firebase 支持团队联系

替换 Gemini 图片模型

查看下表,为您的应用选择替代 Gemini 3.x Image 模型。

Imagen 个模型 Gemini 3.x Image 个模型(“Nano Banana”)
imagen-4.0-fast-generate-001 gemini-3.1-flash-image(思考等级为 MINIMAL
imagen-4.0-generate-001 gemini-3.1-flash-image(思考等级为 HIGH
imagen-4.0-ultra-generate-001 gemini-3-pro-image
imagen-3.0-capability-001 gemini-3.1-flash-image

迁移您的应用

本部分展示了从 Imagen 模型迁移到 Gemini 图片模型的前后示例。

根据文字生成图片

点击您的 Gemini API 提供商,以查看此页面上特定于提供商的内容和代码。

如需根据文本生成图片,请通过做出以下更改来迁移您的应用:

  • 使用适当的替代 Gemini 图片模型(例如 gemini-3.1-flash-image)。

  • 创建 GenerativeModel 实例(而不是 ImagenModel 实例)。

  • 更新模型配置选项,以适应 Gemini 图片模型。

    • 在此配置中,将响应模态设置为 IMAGE
      请注意,Gemini 图片模型可以配置为同时返回图片文本。

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_IMAGE_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_IMAGE_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_IMAGE_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_IMAGE_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_IMAGE_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_IMAGE_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.
  }
}

替换配置选项

本部分介绍了各种模型配置选项的替代方案,以帮助控制模型的回答。

安全设置

您可以使用 ImagenSafetySettingsImagen 模型配置安全设置。不过,对于 Gemini 图片模型,您需要迁移到使用 SafetySetting

模型配置参数

您可以使用 ImagenGenerationConfig 配置 Imagen 模型。不过,对于 Gemini 图片模型,您需要迁移到使用 GenerationConfig 和可选的嵌套 ImageConfig(从 2026 年 5 月初发布的 SDK 版本开始提供)。

GenerationConfig 中,将响应模态设置为 IMAGE(如本指南前面部分中的“之后”代码示例所示)。请注意,您可以选择将 Gemini 图片模型配置为同时返回 IMAGE TEXT

请查看下表,了解如何将模型配置参数从 Imagen 迁移到 Gemini 图片模型:

Imagen 个模型 Gemini 3.x Image 个模型(“Nano Banana”)
addWatermark

不支持

Gemini 图片模型始终会返回带有 SynthID 水印的生成图片。

aspectRatio

ImageConfig 中使用 aspectRatio

如需查看代码示例和支持的值,请参阅 Gemini 图片模型指南中的配置图片生成

imageFormat

不支持

Gemini 图片模型始终以 PNG 格式返回生成的图片。

negativePrompt

不支持

请注意,否定提示是一项旧版功能,自 imagen-3.0-generate-002 起(或在任何 Imagen 4 模型中)就不再受支持。

numberOfImages

不支持

Gemini 图片模型始终会返回一张生成的图片。
作为一种解决方法,您可以循环运行生成操作,以实现相同的结果。请注意,候选数量不能作为替代方案。

personGeneration

不支持

默认情况下,Gemini 图片模型允许生成人物图片。