Gemini API'yi kullanarak resim dosyalarını analiz etme

Gemini modelinden, sağladığınız resim dosyalarını satır içi (Base64 olarak kodlanmış) veya URL aracılığıyla analiz etmesini isteyebilirsiniz. Firebase AI Logic kullandığınızda bu isteği doğrudan uygulamanızdan gönderebilirsiniz.

Bu özellik sayesinde şunları yapabilirsiniz:

  • Altyazı oluşturma veya görsellerle ilgili soruları yanıtlama
  • Bir resim hakkında kısa bir hikaye veya şiir yazma
  • Bir resimdeki nesneleri algılayıp sınırlayıcı kutu koordinatlarını döndürme
  • Bir grup resmi duygu, stil veya başka bir özelliğe göre etiketleme ya da kategorize etme

Kod örneklerine git Yayınlanan yanıtlar için koda git


Görüntülerle çalışmayla ilgili ek seçenekler için diğer kılavuzlara göz atın
Yapılandırılmış çıkış oluşturma Çok turlu sohbet Cihaz üzerinde görüntüleri analiz etme Görüntü oluşturma

Başlamadan önce

Bu sayfada sağlayıcıya özel içerikleri ve kodu görüntülemek için Gemini API sağlayıcınızı tıklayın.

Henüz yapmadıysanız başlangıç kılavuzunu tamamlayın. Bu kılavuzda Firebase projenizi ayarlama, uygulamanızı Firebase'e bağlama, SDK'yı ekleme, seçtiğiniz Gemini API sağlayıcısı için arka uç hizmetini başlatma ve GenerativeModel örneği oluşturma hakkında bilgi verilmektedir.

İstemlerinizi test etmek ve yinelemek, hatta oluşturulmuş bir kod snippet'i almak için Google AI Studio'ı kullanmanızı öneririz.

Resim dosyalarından (base64 kodlu) metin oluşturma

Bu örneği denemeden önce projenizi ve uygulamanızı ayarlamak için bu kılavuzun Başlamadan önce bölümünü tamamlayın.Bu bölümde, seçtiğiniz Gemini API sağlayıcı için bir düğmeyi de tıklayarak bu sayfada sağlayıcıya özel içerikleri görebilirsiniz.

Bir Gemini modelinden, metin ve resimlerle istem oluşturarak metin üretmesini isteyebilirsiniz. Her giriş dosyasının mimeType ve dosyanın kendisini sağlayın. Giriş dosyalarıyla ilgili koşulları ve önerileri bu sayfanın ilerleyen bölümlerinde bulabilirsiniz.

Swift

Metin ve resimlerden oluşan çok formatlı girişlerden metin oluşturmak için generateContent() işlevini çağırabilirsiniz.

Tek dosya girişi


import FirebaseAI

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

Birden fazla dosya girişi


import FirebaseAI

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

Metin ve resimlerden oluşan çok formatlı girişlerden metin oluşturmak için generateContent() işlevini çağırabilirsiniz.

Kotlin'de bu SDK'daki yöntemler askıya alma işlevleridir ve Coroutine kapsamından çağrılmaları gerekir.

Tek dosya girişi


// 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 = generativeModel.generateContent(prompt)
print(response.text)

Birden fazla dosya girişi

Kotlin'de bu SDK'daki yöntemler askıya alma işlevleridir ve Coroutine kapsamından çağrılmaları gerekir.

// 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 = generativeModel.generateContent(prompt)
print(response.text)

Java

Metin ve resimlerden oluşan çok formatlı girişlerden metin oluşturmak için generateContent() işlevini çağırabilirsiniz.

Java için bu SDK'daki yöntemler bir ListenableFuture döndürür.

Tek dosya girişi


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

Birden fazla dosya girişi


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

Metin ve resimlerden oluşan çok formatlı girişlerden metin oluşturmak için generateContent() işlevini çağırabilirsiniz.

Tek dosya girişi


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();

Birden fazla dosya girişi


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

Metin ve resimlerden oluşan çok formatlı girişlerden metin oluşturmak için generateContent() işlevini çağırabilirsiniz.

Tek dosya girişi


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

Birden fazla dosya girişi


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

Unity

Metin ve resimlerden oluşan çok formatlı girişlerden metin oluşturmak için GenerateContentAsync() işlevini çağırabilirsiniz.

Tek dosya girişi


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.");

Birden fazla dosya girişi


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.");

Kullanım alanınıza ve uygulamanıza uygun bir model seçmeyi öğrenin.

Yanıtı akış şeklinde göster

Bu örneği denemeden önce projenizi ve uygulamanızı ayarlamak için bu kılavuzun Başlamadan önce bölümünü tamamlayın.Bu bölümde, seçtiğiniz Gemini API sağlayıcı için bir düğmeyi de tıklayarak bu sayfada sağlayıcıya özel içerikleri görebilirsiniz.

Model oluşturma işleminden gelen sonucun tamamını beklemek yerine akış özelliğini kullanarak kısmi sonuçları işleyebilir ve daha hızlı etkileşimler elde edebilirsiniz. Yanıtı yayınlamak için generateContentStream işlevini çağırın.



Giriş resim dosyalarıyla ilgili koşullar ve öneriler

Satır içi veri olarak sağlanan bir dosyanın aktarım sırasında base64 olarak kodlandığını ve bunun da isteğin boyutunu artırdığını unutmayın. İstek çok büyükse HTTP 413 hatası alırsınız.

Aşağıdaki konular hakkında ayrıntılı bilgi edinmek için "Desteklenen giriş dosyaları ve Vertex AI Gemini API ile ilgili şartlar" bölümüne bakın:

Desteklenen resim MIME türleri

Gemini Çok formatlı modeller aşağıdaki resim MIME türlerini destekler:

Resim MIME türü Gemini 2.0 Flash Gemini 2.0 Flash‑Lite
PNG - image/png
JPEG - image/jpeg
WebP - image/webp

İstek başına sınırlar

Bir resimdeki piksel sayısı için belirli bir sınır yoktur. Ancak daha büyük resimler, orijinal en boy oranları korunarak maksimum 3072 x 3072 çözünürlüğe sığacak şekilde küçültülür ve doldurulur.

İstem isteğinde izin verilen maksimum resim dosyası sayısı şöyledir:

  • Gemini 2.0 Flash ve Gemini 2.0 Flash‑Lite: 3.000 resim



Başka ne yapabilirsin?

  • Modele uzun istemler göndermeden önce jetonları nasıl sayacağınızı öğrenin.
  • AyarlaCloud Storage for Firebase Böylece çok formatlı isteklerinize büyük dosyalar ekleyebilir ve istemlerde dosya sağlamak için daha yönetilebilir bir çözüm elde edebilirsiniz. Dosyalar; resim, PDF, video ve ses içerebilir.
  • Aşağıdakiler de dahil olmak üzere üretime hazırlanma hakkında düşünmeye başlayın (üretim yapılacaklar listesine bakın):
    • Firebase App Check kurarak Gemini API'ı yetkisiz istemcilerin kötüye kullanımına karşı koruyun.
    • Yeni bir uygulama sürümü yayınlamadan uygulamanızdaki değerleri (ör. model adı) güncellemek için Firebase Remote Config entegrasyonu.

Diğer özellikleri deneyin

İçerik oluşturmayı kontrol etme hakkında bilgi

Ayrıca istemler ve model yapılandırmalarıyla denemeler yapabilir, hatta Google AI Studio kullanarak oluşturulmuş bir kod snippet'i alabilirsiniz.

Desteklenen modeller hakkında daha fazla bilgi

Çeşitli kullanım alanları için kullanılabilen modeller, bu modellerin kotaları ve fiyatlandırması hakkında bilgi edinin.


Firebase AI Logic ile ilgili deneyiminiz hakkında geri bildirim verme