ניתוח של קובצי תמונה באמצעות Gemini API

אתם יכולים לבקש ממודל Gemini לנתח קובצי תמונות שאתם מספקים, או בתוך השורה (בקידוד base64) או באמצעות כתובת URL. כשמשתמשים ב-Firebase AI Logic, אפשר לשלוח את הבקשה הזו ישירות מהאפליקציה.

היכולת הזו מאפשרת לכם:

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

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

דילוג לדוגמאות קוד

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


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

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

כדי לראות תוכן וקוד שספציפיים לספק, לוחצים על הספק Gemini API בדף הזה.

אם עדיין לא עשיתם את זה, כדאי לעיין במדריך לתחילת העבודה, שבו מוסבר איך להגדיר את פרויקט Firebase, לקשר את האפליקציה ל-Firebase, להוסיף את ה-SDK, לאתחל את שירות לקצה העורפי עבור ספק Gemini API שבחרתם וליצור מופע GenerativeModel.

כדי לבדוק את ההנחיות ולשפר אותן, מומלץ להשתמש ב-Google AI Studio.

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

המדריך הזה עוסק ביצירת טקסט מקלט של תמונה, והוא רלוונטי למודלים הבאים של Gemini:

  • gemini-4-argon
  • ‫gemini-3.8-flash (והגרסאות הישנות יותר gemini-3.7-flash,‏ gemini-3.6-flash ו-gemini-3.5-flash)
  • ‫gemini-3.5-flash-lite (וגם gemini-3.1-flash-lite הישן יותר)

גם מודלים של gemini-3.1-pro-preview ומודלים לשימוש כללי של Gemini 2.5 (שהשימוש בהם הוצא משימוש) תומכים ביכולת הזו.

יצירת טקסט מקובצי תמונות (בקידוד base64)

לפני שמנסים את הדוגמה הזו, צריך להשלים את השלבים שמפורטים בקטע לפני שמתחילים במדריך הזה כדי להגדיר את הפרויקט והאפליקציה.
בקטע הזה, צריך גם ללחוץ על לחצן של ספק Gemini API שבחרתם כדי שיוצג בדף הזה תוכן שספציפי לספק.

אתם יכולים לבקש ממודל Gemini ליצור טקסט באמצעות הנחיות שכוללות טקסט ותמונות – על ידי ציון ה-mimeType של כל קובץ קלט והקובץ עצמו. בהמשך הדף מפורטות הדרישות וההמלצות לקובצי קלט.

Swift

אפשר להפעיל את generateContent() כדי ליצור טקסט מקלט מולטי-מודאלי של טקסט ותמונות.

קלט של קובץ אחד


import FirebaseAILogic

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

// Create a `GenerativeModel` instance with a model that supports your use case.
let model = ai.generativeModel(modelName: "gemini-3.8-flash")


guard let image = UIImage(systemName: "bicycle") else { fatalError() }

// Provide a text prompt to include with the image
let prompt = "What's in this picture?"

// To generate text output, call generateContent and pass in the prompt
let response = try await model.generateContent(image, prompt)
print(response.text ?? "No text in response.")

קלט של כמה קבצים


import FirebaseAILogic

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

// Create a `GenerativeModel` instance with a model that supports your use case.
let model = ai.generativeModel(modelName: "gemini-3.8-flash")


guard let image1 = UIImage(systemName: "car") else { fatalError() }
guard let image2 = UIImage(systemName: "car.2") else { fatalError() }

// Provide a text prompt to include with the images
let prompt = "What's different between these pictures?"

// To generate text output, call generateContent and pass in the prompt
let response = try await model.generateContent(image1, image2, prompt)
print(response.text ?? "No text in response.")

Kotlin

אפשר להתקשר אל generateContent() כדי ליצור טקסט דינמי מבוסס-AI מקלט מולטי-מודאלי של טקסט ותמונות.

ב-Kotlin, השיטות ב-SDK הזה הן פונקציות השהיה וצריך לקרוא להן מהיקף Coroutine.

קלט של קובץ אחד


// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports your use case.
val model = Firebase.ai(backend = GenerativeBackend.googleAI())
                        .generativeModel("gemini-3.8-flash")


// Loads an image from the app/res/drawable/ directory
val bitmap: Bitmap = BitmapFactory.decodeResource(resources, R.drawable.sparky)

// Provide a prompt that includes the image specified above and text
val prompt = content {
  image(bitmap)
  text("What developer tool is this mascot from?")
}

// To generate text output, call generateContent with the prompt
val response = model.generateContent(prompt)
print(response.text)

קלט של כמה קבצים

ב-Kotlin, השיטות ב-SDK הזה הן פונקציות השהיה וצריך לקרוא להן מהיקף Coroutine.

// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports your use case.
val model = Firebase.ai(backend = GenerativeBackend.googleAI())
                        .generativeModel("gemini-3.8-flash")


// Loads an image from the app/res/drawable/ directory
val bitmap1: Bitmap = BitmapFactory.decodeResource(resources, R.drawable.sparky)
val bitmap2: Bitmap = BitmapFactory.decodeResource(resources, R.drawable.sparky_eats_pizza)

// Provide a prompt that includes the images specified above and text
val prompt = content {
  image(bitmap1)
  image(bitmap2)
  text("What is different between these pictures?")
}

// To generate text output, call generateContent with the prompt
val response = model.generateContent(prompt)
print(response.text)

Java

אפשר להפעיל את generateContent() כדי ליצור טקסט מקלט מולטי-מודאלי של טקסט ותמונות.

ב-Java, השיטות ב-SDK הזה מחזירות ListenableFuture.

קלט של קובץ אחד


// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports your use case.
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
        .generativeModel("gemini-3.8-flash");

// Use the GenerativeModelFutures Java compatibility layer which offers
// support for ListenableFuture and Publisher APIs
GenerativeModelFutures model = GenerativeModelFutures.from(ai);


Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.sparky);

// Provide a prompt that includes the image specified above and text
Content content = new Content.Builder()
        .addImage(bitmap)
        .addText("What developer tool is this mascot from?")
        .build();

// To generate text output, call generateContent with the prompt
ListenableFuture<GenerateContentResponse> response = model.generateContent(content);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
    @Override
    public void onSuccess(GenerateContentResponse result) {
        String resultText = result.getText();
        System.out.println(resultText);
    }

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

קלט של כמה קבצים


// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports your use case.
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
        .generativeModel("gemini-3.8-flash");

// Use the GenerativeModelFutures Java compatibility layer which offers
// support for ListenableFuture and Publisher APIs
GenerativeModelFutures model = GenerativeModelFutures.from(ai);


Bitmap bitmap1 = BitmapFactory.decodeResource(getResources(), R.drawable.sparky);
Bitmap bitmap2 = BitmapFactory.decodeResource(getResources(), R.drawable.sparky_eats_pizza);

// Provide a prompt that includes the images specified above and text
Content prompt = new Content.Builder()
    .addImage(bitmap1)
    .addImage(bitmap2)
    .addText("What's different between these pictures?")
    .build();

// To generate text output, call generateContent with the prompt
ListenableFuture<GenerateContentResponse> response = model.generateContent(prompt);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
    @Override
    public void onSuccess(GenerateContentResponse result) {
        String resultText = result.getText();
        System.out.println(resultText);
    }

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

Web

אפשר להפעיל את generateContent() כדי ליצור טקסט מקלט מולטי-מודאלי של טקסט ותמונות.

קלט של קובץ אחד


import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend } 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-3.8-flash" });


// 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 {
    type: "inlineData",
    inlineData: { data: await base64EncodedDataPromise, mimeType: file.type },
  };
}

async function run() {
  // Provide a text prompt to include with the image
  const prompt = "What do you see?";

  const fileInputEl = document.querySelector("input[type=file]");
  const imagePart = await fileToGenerativePart(fileInputEl.files[0]);

  // To generate text output, call generateContent with the text and image
  const result = await model.generateContent([prompt, imagePart]);

  const response = result.response;
  const text = response.text();
  console.log(text);
}

run();

קלט של כמה קבצים


import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend } 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-3.8-flash" });


// 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 {
    type: "inlineData",
    inlineData: { data: await base64EncodedDataPromise, mimeType: file.type },
  };
}

async function run() {
  // Provide a text prompt to include with the images
  const prompt = "What's different between these pictures?";

  // Prepare images for input
  const fileInputEl = document.querySelector("input[type=file]");
  const imageParts = await Promise.all(
    [...fileInputEl.files].map(fileToGenerativePart)
  );

  // To generate text output, call generateContent with the text and images
  const result = await model.generateContent([prompt, ...imageParts]);

  const response = result.response;
  const text = response.text();
  console.log(text);
}

run();

Dart

אפשר להתקשר אל generateContent() כדי ליצור טקסט דינמי מבוסס-AI מקלט מולטי-מודאלי של טקסט ותמונות.

קלט של קובץ אחד


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.
// Create a `GenerativeModel` instance with a model that supports your use case.
final model =
      FirebaseAI.googleAI().generativeModel(model: 'gemini-3.8-flash');


// Provide a text prompt to include with the image
final prompt = TextPart("What's in the picture?");
// Prepare images for input
final image = await File('image0.jpg').readAsBytes();
final imagePart = InlineDataPart('image/jpeg', image);

// To generate text output, call generateContent with the text and image
final response = await model.generateContent([
  Content.multi([prompt,imagePart])
]);
print(response.text);

קלט של כמה קבצים


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.
// Create a `GenerativeModel` instance with a model that supports your use case.
final model =
      FirebaseAI.googleAI().generativeModel(model: 'gemini-3.8-flash');


final (firstImage, secondImage) = await (
  File('image0.jpg').readAsBytes(),
  File('image1.jpg').readAsBytes()
).wait;
// Provide a text prompt to include with the images
final prompt = TextPart("What's different between these pictures?");
// Prepare images for input
final imageParts = [
  InlineDataPart('image/jpeg', firstImage),
  InlineDataPart('image/jpeg', secondImage),
];

// To generate text output, call generateContent with the text and images
final response = await model.generateContent([
  Content.multi([prompt, ...imageParts])
]);
print(response.text);

Unity

אפשר להתקשר אל GenerateContentAsync() כדי ליצור טקסט דינמי מבוסס-AI מקלט מולטי-מודאלי של טקסט ותמונות.

קלט של קובץ יחיד


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 model that supports your use case.
var model = ai.GetGenerativeModel(modelName: "gemini-3.8-flash");


// Convert a Texture2D into InlineDataParts
var grayImage = ModelContent.InlineData("image/png",
      UnityEngine.ImageConversion.EncodeToPNG(UnityEngine.Texture2D.grayTexture));

// Provide a text prompt to include with the image
var prompt = ModelContent.Text("What's in this picture?");

// To generate text output, call GenerateContentAsync and pass in the prompt
var response = await model.GenerateContentAsync(new [] { grayImage, prompt });
UnityEngine.Debug.Log(response.Text ?? "No text in response.");

קלט של כמה קבצים


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 model that supports your use case.
var model = ai.GetGenerativeModel(modelName: "gemini-3.8-flash");


// Convert Texture2Ds into InlineDataParts
var blackImage = ModelContent.InlineData("image/png",
      UnityEngine.ImageConversion.EncodeToPNG(UnityEngine.Texture2D.blackTexture));
var whiteImage = ModelContent.InlineData("image/png",
      UnityEngine.ImageConversion.EncodeToPNG(UnityEngine.Texture2D.whiteTexture));

// Provide a text prompt to include with the images
var prompt = ModelContent.Text("What's different between these pictures?");

// To generate text output, call GenerateContentAsync and pass in the prompt
var response = await model.GenerateContentAsync(new [] { blackImage, whiteImage, prompt });
UnityEngine.Debug.Log(response.Text ?? "No text in response.");

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

הצגת התשובה באופן שוטף

לפני שמנסים את הדוגמה הזו, צריך להשלים את השלבים בקטע לפני שמתחילים במדריך הזה כדי להגדיר את הפרויקט והאפליקציה.
בקטע הזה, צריך גם ללחוץ על כפתור של ספק Gemini API שבחרתם כדי לראות תוכן ספציפי לספק בדף הזה.

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



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

שימו לב שקובץ שסופק כנתונים מוטבעים מקודד ל-base64 במהלך ההעברה, מה שמגדיל את גודל הבקשה. אם הבקשה גדולה מדי, תתקבל שגיאת HTTP 413.

במאמר 'קבצי קלט נתמכים ודרישות' מפורט מידע על הנושאים הבאים:

סוגי MIME נתמכים של תמונות

המודלים המולטי-מודאליים של Gemini תומכים בסוגי ה-MIME הבאים של תמונות:

  • ‫PNG – image/png
  • JPEG – image/jpeg
  • ‫WebP – ‏image/webp

מגבלות לכל בקשה

אין הגבלה ספציפית על מספר הפיקסלים בתמונה. עם זאת, תמונות גדולות יותר מוקטנות ונוספים להן שוליים כדי להתאים לרזולוציה מקסימלית של 3,072 x‏ 3,072, תוך שמירה על יחס הגובה-רוחב המקורי שלהן.

מספר הקבצים המקסימלי לבקשה: 3,000 קובצי תמונות



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

לנסות יכולות אחרות

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

אפשר גם להתנסות בהנחיות ובהגדרות של המודל, ואפילו לקבל קטע קוד שנוצר באמצעות Google AI Studio.

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

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


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