تحليل ملفات الصور باستخدام واجهة برمجة التطبيقات Gemini

يمكنك أن تطلب من نموذج Gemini تحليل ملفات الصور التي تقدّمها إما مضمّنة (بترميز base64) أو من خلال عنوان URL. عند استخدام Firebase AI Logic، يمكنك تقديم هذا الطلب مباشرةً من تطبيقك على الأجهزة الجوّالة أو تطبيق الويب (مثل تطبيق Apple (Swift) أو Android (Kotlin / Java) أو الويب (JavaScript) أو Flutter (Dart) أو Unity).

باستخدام هذه الميزة، يمكنك إجراء ما يلي:

  • إنشاء شرح أو الإجابة عن أسئلة حول الصور
  • كتابة قصة قصيرة أو قصيدة عن صورة
  • رصد العناصر في صورة وعرض إحداثيات المربّعات المحيطة بها
  • تصنيف مجموعة من الصور حسب المشاعر أو الأسلوب أو أي سمة أخرى

يتناول هذا الدليل كيفية إنشاء نص من إدخال صورة، ولكن يمكنك أيضًا إنشاء صور من إدخال صور.

الانتقال إلى عيّنات التعليمات البرمجية

الانتقال إلى التعليمات البرمجية للردود المباشرة


يمكنك الاطّلاع على أدلة أخرى للحصول على خيارات إضافية للتعامل مع الصور
إنشاء مخرجات منظَّمة محادثة متعددة الجولات تحليل الصور على الجهاز فقط إنشاء الصور

قبل البدء

انقر على مزوّد خدمة Gemini API للاطّلاع على المحتوى والرمز البرمجي الخاصَّين بمزوّد الخدمة على هذه الصفحة.

إذا لم يسبق لك إجراء ذلك، أكمِل دليل البدء الذي يوضّح كيفية إعداد مشروعك على Firebase وربط تطبيقك بمنصة Firebase وإضافة حزمة تطوير البرامج (SDK) وإعداد خدمة الخلفية لمزوّد Gemini API الذي اخترته وإنشاء مثيل GenerativeModel.

لاختبار الطلبات وتحسينها، ننصحك باستخدام Google AI Studio.

النماذج التي تتيح هذه الميزة

يتناول هذا الدليل كيفية إنشاء نصّ من إنشاء الذكاء الاصطناعي من إدخال صورة، وهو ينطبق على نماذج Gemini التالية:

  • gemini-4-hydrogen
  • gemini-4-argon
  • gemini-4-carbon
  • gemini-3.8-flash
  • ‫gemini-3.5-flash-lite (والإصدار الأقدم gemini-3.1-flash-lite)

تتيح نماذج Gemini 3.x Flash القديمة ذات الاستخدام العام هذه الإمكانية، ولكن لا يُنصح باستخدامها بعد الآن بسبب تواريخ الإيقاف القادمة و/أو إعادة التوجيه التلقائي إلى النماذج الأحدث.

إنشاء نصّ من إنشاء الذكاء الاصطناعي من ملفات صور (بترميز 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-4-hydrogen")


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-4-hydrogen")


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() لإنشاء نصّ من إنشاء الذكاء الاصطناعي من إدخال متعدد الوسائط للنصوص والصور.

بالنسبة إلى Kotlin، فإنّ الطرق في حزمة تطوير البرامج (SDK) هذه هي دوال تعليق ويجب استدعاؤها من نطاق الكوروتين.

إدخال ملف واحد


// 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-4-hydrogen")


// 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) هذه هي دوال تعليق ويجب استدعاؤها من نطاق الكوروتين.

// 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-4-hydrogen")


// 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-4-hydrogen");

// 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-4-hydrogen");

// 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-4-hydrogen" });


// 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-4-hydrogen" });


// 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() لإنشاء نصّ من إنشاء الذكاء الاصطناعي من إدخال متعدد الوسائط للنصوص والصور.

إدخال ملف واحد


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-4-hydrogen');


// 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-4-hydrogen');


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() لإنشاء نصّ من إنشاء الذكاء الاصطناعي من إدخال متعدد الوسائط للنصوص والصور.

إدخال ملف واحد


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-4-hydrogen");


// 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-4-hydrogen");


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

الحدود لكل طلب

ما مِن حدّ أقصى لعدد وحدات البكسل في الصورة. ومع ذلك، يتم تصغير الصور الأكبر حجمًا وإضافة مساحة فارغة إليها لتلائم الحد الأقصى للدقة وهو 3072 × 3072 مع الحفاظ على نسبة العرض إلى الارتفاع الأصلية.

الحد الأقصى لعدد الملفات لكل طلب: 3,000 ملف صورة



ما هي المهام الأخرى التي يمكنني تنفيذها؟

تجربة إمكانات أخرى

كيفية التحكّم في إنشاء المحتوى

يمكنك أيضًا تجربة الطلبات وإعدادات النماذج، وحتى الحصول على مقتطف رمز تم إنشاؤه باستخدام Google AI Studio.

مزيد من المعلومات عن النماذج المتوافقة

يمكنك التعرّف على النماذج المتاحة لحالات الاستخدام المختلفة والحصص والأسعار.


تقديم ملاحظات حول تجربتك مع "Firebase AI Logic"