יצירת תמונות באמצעות Imagen


ערכות ה-SDK של Vertex AI in Firebase נותנות לכם גישה למודלים של Imagen 3 (דרך Imagen API) כדי שתוכלו ליצור תמונות מהנחיית טקסט. בעזרת היכולת הזו תוכלו לבצע פעולות כמו:

  • יצירת תמונות מהנחיות שנכתבות בשפה טבעית
  • יצירת תמונות במגוון רחב של פורמטים וסגנונות
  • רינדור של טקסט בתמונות

חשוב לזכור ש-Vertex AI in Firebase עדיין לא תומך בכל התכונות שזמינות לדגמי Imagen. מידע נוסף זמין בקטע יכולות ותכונות נתמכות בהמשך הדף.

מעבר לקוד לקלט טקסט בלבד

לפני שמתחילים

אם עדיין לא עשיתם זאת, כדאי לעיין במדריך למתחילים, שבו מוסבר איך מגדירים את פרויקט Firebase, מחברים את האפליקציה ל-Firebase, מוסיפים את ה-SDK, מאתחלים את השירות Vertex AI ויוצרים מכונה של ImagenModel.

חשוב לוודא שאתם משתמשים בגרסת הספרייה הבאה של Firebase לפחות:
iOS+: v11.9.0 ואילך | Android: v16.2.0 ואילך (BoM: v33.10.0 ואילך) | אינטרנט: v11.4.1 ואילך | Flutter: v1.4.0 ואילך (BoM: v3.8.0 ואילך)

מודלים שתומכים ביכולת הזו

המודלים Imagen 3 תומכים ביצירת תמונות. בקרוב תהיה תמיכה ביצירת תמונות באמצעות מודלים של Gemini 2.0.

יצירת תמונות מקלט של טקסט בלבד

אתם יכולים לבקש ממודל Imagen ליצור תמונות באמצעות הנחיה עם טקסט. אפשר ליצור תמונה אחת או כמה תמונות.

יצירת תמונה אחת מקלט טקסט בלבד

חשוב לוודא שביצעתם את ההוראות בקטע לפני שמתחילים במדריך הזה לפני שאתם מנסים את הדוגמה הזו.

אפשר לבקש ממודל Imagen ליצור תמונה אחת על ידי הוספת הנחיה עם טקסט.

חשוב ליצור מכונה של ImagenModel ולקרוא ל-generateImages.

Swift

import FirebaseVertexAI

// Initialize the Vertex AI service
let vertex = VertexAI.vertexAI()

// Create an `ImagenModel` instance with an Imagen 3 model that supports your use case
let model = vertex.imagenModel(modelName: "imagen-3.0-generate-002")

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

Kotlin

// Using Imagen with Vertex AI in Firebase is in public preview
// It requires opt-in to use the API
@OptIn(PublicPreviewAPI::class)
suspend fun generateImage() {
  // Initialize the Vertex AI service and create an `ImagenModel` instance
  // Specify an Imagen 3 model that supports your use case
  val imagenModel = Firebase.vertexAI.imagenModel("imagen-3.0-generate-002")

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

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

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

  val bitmapImage = image.asBitmap()
}

Java

// Initialize the Vertex AI service and create an `ImagenModel` instance
// Specify an Imagen 3 model that supports your use case
ImagenModel imagenModel = FirebaseVertexAI.getInstance().imagenModel(
        /* modelName */ "imagen-3.0-generate-002");

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<ImagenInlineImage>>() {
    @Override
    public void onSuccess(ImagenGenerationResponse<ImagenInlineImage> 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());

Web

import { initializeApp } from "firebase/app";
import { getVertexAI, getImagenModel } from "firebase/vertexai";

// 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 Vertex AI service
const vertexAI = getVertexAI(firebaseApp);

// Create an `ImagenModel` instance with an Imagen 3 model that supports your use case
const imagenModel = getImagenModel(
  vertexAI,
  {
    model: "imagen-3.0-generate-002"
  }
);

// 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 imagenModel.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];

Dart

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

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

// Initialize the Vertex AI service and create an `ImagenModel` instance
// Specify an Imagen 3 model that supports your use case
final model =
    FirebaseVertexAI.instance.imagenModel(model: 'imagen-3.0-generate-002');

// 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.');
}

כאן מוסבר איך בוחרים מודל, ואם רוצים גם מיקום, שמתאימים לתרחיש לדוגמה ולאפליקציה.

יצירת כמה תמונות ממידע שמוזן בטקסט בלבד

חשוב לוודא שביצעתם את ההוראות בקטע לפני שמתחילים במדריך הזה לפני שאתם מנסים את הדוגמה הזו.

כברירת מחדל, מודלים של Imagen 3 יוצרים רק תמונה אחת לכל בקשה. עם זאת, אפשר לבקש ממודל Imagen ליצור כמה תמונות לכל בקשה על ידי ציון הערך ImagenGenerationConfig בזמן יצירת המכונה ImagenModel.

חשוב ליצור מכונה של ImagenModel ולקרוא ל-generateImages.

Swift

import FirebaseVertexAI

// Initialize the Vertex AI service
let vertex = VertexAI.vertexAI()

// Create an `ImagenModel` instance with an Imagen 3 model that supports your use case
let model = vertex.imagenModel(
  modelName: "imagen-3.0-generate-002",
  // Configure the model to generate multiple images for each request
  // See: https://firebase.google.com/docs/vertex-ai/model-parameters
  generationConfig: ImagenGenerationConfig(numberOfImages: 4)
)

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

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

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

// Handle the generated images
let uiImages =  response.images.compactMap { UIImage(data: $0.data) }

Kotlin

// Using Imagen with Vertex AI in Firebase is in public preview
// It requires opt-in to use the API
@OptIn(PublicPreviewAPI::class)
suspend fun generateImage() {
  // Initialize the Vertex AI service and create an `ImagenModel` instance
  // Specify an Imagen 3 model that supports your use case
  val imagenModel = Firebase.vertexAI.imagenModel(
      modelName = "imagen-3.0-generate-002",
      // Configure the model to generate multiple images for each request
      // See: https://firebase.google.com/docs/vertex-ai/model-parameters
      generationConfig = ImagenGenerationConfig(numberOfImages = 4)
  )

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

  // To generate images, call `generateImages` with the text prompt
  val imageResponse = imagenModel.generateImages(prompt)

  // If fewer images were generated than were requested,
  // then `filteredReason` will describe the reason they were filtered out
  if (imageResponse.filteredReason != null) {
    Log.d(TAG, "FilteredReason: ${imageResponse.filteredReason}")
  }

  for (image in imageResponse.images) {
    val bitmap = image.asBitmap()
    // Use the bitmap to display the image in your UI
  }
}

Java

// Configure the model to generate multiple images for each request
// See: https://firebase.google.com/docs/vertex-ai/model-parameters
ImagenGenerationConfig imagenGenerationConfig = new ImagenGenerationConfig.Builder()
        .setNumberOfImages(4)
        .build();

// Initialize the Vertex AI service and create an `ImagenModel` instance
// Specify an Imagen 3 model that supports your use case
ImagenModel imagenModel = FirebaseVertexAI.getInstance().imagenModel(
        /* modelName */ "imagen-3.0-generate-002",
        /* imageGenerationConfig */ imagenGenerationConfig);

ImagenModelFutures model = ImagenModelFutures.from(imagenModel);

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

// To generate images, call `generateImages` with the text prompt
Futures.addCallback(model.generateImages(prompt), new FutureCallback<ImagenGenerationResponse<ImagenInlineImage>>() {
    @Override
    public void onSuccess(ImagenGenerationResponse<ImagenInlineImage> result) {
        // If fewer images were generated than were requested,
        // then `filteredReason` will describe the reason they were filtered out
        if (result.getFilteredReason() != null){
            Log.d("TAG", "FilteredReason: " + result.getFilteredReason());
        }

        // Handle the generated images
        List<ImagenInlineImage> images = result.getImages();
        for (ImagenInlineImage image : images) {
            Bitmap bitmap = image.asBitmap();
            // Use the bitmap to display the image in your UI
        }
    }

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

Web

import { initializeApp } from "firebase/app";
import { getVertexAI, getImagenModel } from "firebase/vertexai";

// 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 Vertex AI service
const vertexAI = getVertexAI(firebaseApp);

// Create an `ImagenModel` instance with an Imagen 3 model that supports your use case
const imagenModel = getImagenModel(
  vertexAI,
  {
    model: "imagen-3.0-generate-002",
    // Configure the model to generate multiple images for each request
    // See: https://firebase.google.com/docs/vertex-ai/model-parameters
    generationConfig: {
      numberOfImages: 4
    }
  }
);

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

// To generate images, call `generateImages` with the text prompt
const response = await imagenModel.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 images = response.images[0];

Dart

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

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

// Initialize the Vertex AI service and create an `ImagenModel` instance
// Specify an Imagen 3 model that supports your use case
final model = FirebaseVertexAI.instance.imagenModel(
  model: 'imagen-3.0-generate-002',
  // Configure the model to generate multiple images for each request
  // See: https://firebase.google.com/docs/vertex-ai/model-parameters
  generationConfig: ImagenGenerationConfig(numberOfImages: 4),
);

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

// To generate images, call `generateImages` with the text prompt
final 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 != null) {
  print(response.filteredReason);
}

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

כאן מוסבר איך בוחרים מודל, ואם רוצים גם מיקום, שמתאימים לתרחיש לדוגמה ולאפליקציה.

תכונות נתמכות ודרישות

המודלים של Imagen 3 מציעים הרבה תכונות שקשורות ליצירת תמונות. בקטע הזה מוסבר מה נתמך כשמשתמשים במודלים עם Vertex AI in Firebase.

יכולות ותכונות נתמכות

Vertex AI in Firebase תומך בתכונות האלה של דגמי Imagen 3.

  • יצירת אנשים ופנים (בתנאי שפרויקט Firebase שלכם קיבל אישור מ-Google Cloud)

  • יצירת טקסט בתוך תמונות שנוצרו

  • הוספת סימן מים לתמונות שנוצרו

  • הגדרת פרמטרים ליצירת תמונות, כמו מספר התמונות שנוצרות, יחס גובה-רוחב והוספת סימן מים

  • הגדרת הגדרות הבטיחות

Vertex AI in Firebase לא תומך בתכונות המתקדמות האלה של דגמי Imagen 3.

חשוב לזכור שרוב התכונות האלה מחייבות אתכם להופיע ברשימת משתמשים שאושרו, גם אם אתם משתמשים במודלים של Imagen בצד השרת.

  • תכונות של עריכה או מניפולציה של תמונות, כולל התאמת תמונות

  • הוספת תמונות לבקשה למודלים (למשל, לצורך למידת few-shot)

  • אימות של סימני מים דיגיטליים באמצעות ערכות ה-SDK
    כדי לוודא שלתמונה יש סימן מים, אפשר להעלות אותה ל-Vertex AI Studio באמצעות הכרטיסייה Media.

  • יצירת 'תמונות חיות' מטקסט (יצירת קובץ MP4)

  • יצירת תמונות באמצעות סגנון מוגדר מראש

  • הגדרת השפה של טקסט הקלט

  • הפעלת includeSafetyAttributes, כלומר אי אפשר להחזיר את הערכים safetyAttributes.categories ו-safetyAttributes.scores

  • השבתת שיפור ההנחיה (הפרמטר enhancePrompt). המשמעות היא שכלי לשכתוב הנחיות שמבוסס על LLM תמיד יוסיף באופן אוטומטי פרטים נוספים להנחיה שסופקה כדי לספק תמונות באיכות גבוהה יותר שמשקפות טוב יותר את ההנחיה שסופקה.

  • כתיבת תמונה שנוצרה ישירות ב-Google Cloud Storage כחלק מהתגובה מהמודל (הפרמטר storageUri). במקום זאת, התמונות תמיד מוחזר בתגובה כבייט של תמונה בקידוד base64.
    אם רוצים להעלות תמונה שנוצרה ב-Cloud Storage, אפשר להשתמש ב-Cloud Storage for Firebase.

מפרטים ומגבלות

מגבלות (לכל בקשה) Imagen 3 Imagen 3 Fast
המספר המקסימלי של אסימוני קלט 480 אסימונים 480 אסימונים
מספר התמונות המקסימלי בפלט 4 תמונות 4 תמונות
רזולוציות תמונות פלט נתמכות (פיקסלים)
  • 1,024x1,024 פיקסלים (יחס גובה-רוחב של 1:1)
  • 896x1280 (יחס גובה-רוחב של 3:4)
  • 1280x896 (יחס גובה-רוחב של 4:3)
  • 768x1408 (יחס גובה-רוחב של 9:16)
  • 1408x768 (יחס גובה-רוחב של 16:9)
  • 1024x1024 פיקסלים (יחס גובה-רוחב של 1:1)
  • 896x1280 (יחס גובה-רוחב של 3:4)
  • 1280x896 (יחס גובה-רוחב של 4:3)
  • 768x1408 (יחס גובה-רוחב של 9:16)
  • 1408x768 (יחס גובה-רוחב של 16:9)



מה עוד אפשר לעשות?

איך שולטים ביצירת תוכן

מידע נוסף על המודלים הנתמכים

כאן תוכלו לקרוא מידע נוסף על המודלים הזמינים לתרחישי שימוש שונים, על המכסות ועל התמחור שלהם.


שליחת משוב על חוויית השימוש ב-Vertex AI in Firebase