فایل های تصویری را با استفاده از API جمینی تجزیه و تحلیل کنید

شما می‌توانید از یک مدل Gemini بخواهید فایل‌های تصویری که شما ارائه می‌دهید را چه به صورت درون‌خطی (با کدگذاری base64) و چه از طریق URL تجزیه و تحلیل کند. وقتی از Firebase AI Logic استفاده می‌کنید، می‌توانید این درخواست را مستقیماً از برنامه خود انجام دهید.

با این قابلیت، می‌توانید کارهایی مانند موارد زیر را انجام دهید:

  • ایجاد زیرنویس یا پاسخ به سوالات در مورد تصاویر
  • یک داستان کوتاه یا شعر در مورد یک تصویر بنویسید
  • اشیاء را در یک تصویر تشخیص داده و مختصات کادر محصورکننده آنها را برمی‌گرداند
  • مجموعه‌ای از تصاویر را بر اساس احساسات، سبک یا سایر ویژگی‌ها برچسب‌گذاری یا دسته‌بندی کنید

پرش به نمونه‌های کد پرش به کد برای پاسخ‌های استریم‌شده


برای گزینه‌های بیشتر برای کار با تصاویر، به راهنماهای دیگر مراجعه کنید.
تولید خروجی ساختاریافته چت چند نوبتی تجزیه و تحلیل تصاویر روی دستگاه تولید تصاویر

قبل از اینکه شروع کنی

برای مشاهده محتوا و کد مخصوص ارائه‌دهنده در این صفحه، روی ارائه‌دهنده API Gemini خود کلیک کنید.

اگر هنوز این کار را نکرده‌اید، راهنمای شروع به کار را تکمیل کنید، که نحوه راه‌اندازی پروژه Firebase، اتصال برنامه به Firebase، افزودن SDK، راه‌اندازی سرویس backend برای ارائه‌دهنده API انتخابی Gemini و ایجاد یک نمونه GenerativeModel را شرح می‌دهد.

برای آزمایش و تکرار روی درخواست‌هایتان، توصیه می‌کنیم از Google AI Studio استفاده کنید.

تولید متن از فایل‌های تصویری (با کدگذاری base64)

قبل از امتحان کردن این نمونه، بخش «قبل از شروع» این راهنما را برای راه‌اندازی پروژه و برنامه خود تکمیل کنید.
در آن بخش، شما همچنین می‌توانید روی دکمه‌ای برای ارائه‌دهنده‌ی API Gemini انتخابی خود کلیک کنید تا محتوای خاص ارائه‌دهنده را در این صفحه مشاهده کنید .

شما می‌توانید از یک مدل Gemini بخواهید با ارائه متن و تصاویر، متن تولید کند - و mimeType هر فایل ورودی و خود فایل را ارائه دهد. الزامات و توصیه‌هایی برای فایل‌های ورودی را بعداً در این صفحه بیابید.

سویفت

شما می‌توانید 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-2.5-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-2.5-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() برای تولید متن از ورودی چندوجهی متن و تصاویر فراخوانی کنید.

برای کاتلین، متدهای موجود در این SDK توابع suspend هستند و باید از یک scope کوروتین فراخوانی شوند.

ورودی تک فایل


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

ورودی چندگانه فایل

برای کاتلین، متدهای موجود در این SDK توابع suspend هستند و باید از یک scope کوروتین فراخوانی شوند.

// 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-2.5-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() برای تولید متن از ورودی چندوجهی متن و تصاویر فراخوانی کنید.

برای جاوا، متدهای موجود در این 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-2.5-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-2.5-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-2.5-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 {
    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-2.5-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 {
    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-2.5-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-2.5-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);

وحدت

شما می‌توانید تابع 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-2.5-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-2.5-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.");

یاد بگیرید که چگونه یک مدل را انتخاب کنیدمناسب برای مورد استفاده و برنامه شما.

پاسخ را پخش کنید

قبل از امتحان کردن این نمونه، بخش «قبل از شروع» این راهنما را برای راه‌اندازی پروژه و برنامه خود تکمیل کنید.
در آن بخش، شما همچنین می‌توانید روی دکمه‌ای برای ارائه‌دهنده‌ی API Gemini انتخابی خود کلیک کنید تا محتوای خاص ارائه‌دهنده را در این صفحه مشاهده کنید .

شما می‌توانید با منتظر نماندن برای کل نتیجه از تولید مدل، و در عوض استفاده از استریمینگ برای مدیریت نتایج جزئی، به تعاملات سریع‌تری دست یابید. برای استریمینگ پاسخ، generateContentStream فراخوانی کنید.



الزامات و توصیه‌ها برای فایل‌های تصویر ورودی

توجه داشته باشید که فایلی که به عنوان داده درون‌خطی ارائه می‌شود، در حین انتقال به base64 کدگذاری می‌شود که باعث افزایش اندازه درخواست می‌شود. اگر درخواست خیلی بزرگ باشد، خطای HTTP 413 دریافت خواهید کرد.

برای کسب اطلاعات دقیق در مورد موارد زیر، به صفحه «فایل‌های ورودی پشتیبانی‌شده و الزامات» مراجعه کنید:

انواع MIME تصویر پشتیبانی شده

مدل‌های چندوجهی Gemini از انواع MIME تصویر زیر پشتیبانی می‌کنند:

  • PNG - image/png
  • JPEG - image/jpeg
  • WebP - image/webp

محدودیت‌ها به ازای هر درخواست

محدودیت خاصی برای تعداد پیکسل‌های یک تصویر وجود ندارد. با این حال، تصاویر بزرگتر کوچک شده و برای رسیدن به حداکثر وضوح 3072 در 3072 و در عین حال حفظ نسبت ابعاد اصلی، پر می‌شوند.

حداکثر تعداد فایل در هر درخواست: ۳۰۰۰ فایل تصویری



چه کار دیگری می‌توانید انجام دهید؟

  • یاد بگیرید که چگونه قبل از ارسال دستورات طولانی به مدل، توکن‌ها را بشمارید .
  • Cloud Storage for Firebase تنظیم کنید تا بتوانید فایل‌های بزرگ را در درخواست‌های چندوجهی خود بگنجانید و یک راه‌حل مدیریت‌شده‌تر برای ارائه فایل‌ها در اعلان‌ها داشته باشید. فایل‌ها می‌توانند شامل تصاویر، فایل‌های PDF، ویدیو و صدا باشند.
  • شروع به فکر کردن در مورد آماده‌سازی برای تولید کنید (به چک لیست تولید مراجعه کنید)، از جمله:

قابلیت‌های دیگر را امتحان کنید

آموزش کنترل تولید محتوا

شما همچنین می‌توانید با استفاده از دستورات و پیکربندی‌های مدل، آزمایش کنید و حتی یک قطعه کد تولید شده با استفاده از Google AI Studio دریافت کنید.

درباره مدل‌های پشتیبانی‌شده بیشتر بدانید

درباره مدل‌های موجود برای موارد استفاده مختلف و سهمیه‌ها و قیمت‌گذاری آنها اطلاعات کسب کنید.


درباره تجربه خود با Firebase AI Logic بازخورد دهید