Menganalisis file gambar menggunakan Gemini API

Anda dapat meminta model Gemini untuk menganalisis file gambar yang Anda berikan secara inline (enkode base64) atau melalui URL. Saat menggunakan Firebase AI Logic, Anda dapat membuat permintaan ini langsung dari aplikasi.

Dengan kemampuan ini, Anda dapat melakukan hal-hal seperti:

  • Membuat teks atau menjawab pertanyaan tentang gambar
  • Menulis cerita pendek atau puisi tentang gambar
  • Mendeteksi objek dalam gambar dan menampilkan koordinat kotak pembatas untuk objek tersebut
  • Memberi label atau mengategorikan kumpulan gambar untuk sentimen, gaya, atau karakteristik lainnya

Langsung ke contoh kode Langsung ke kode untuk respons yang di-streaming


Lihat panduan lain untuk mengetahui opsi tambahan dalam menangani gambar
Buat output terstruktur Chat multi-giliran Analisis gambar di perangkat Buat gambar

Sebelum memulai

Klik penyedia Gemini API untuk melihat konten dan kode khusus penyedia di halaman ini.

Jika Anda belum melakukannya, selesaikan panduan memulai, yang menjelaskan cara menyiapkan project Firebase, menghubungkan aplikasi ke Firebase, menambahkan SDK, menginisialisasi layanan backend untuk penyedia Gemini API yang Anda pilih, dan membuat instance GenerativeModel.

Untuk menguji dan melakukan iterasi pada perintah Anda, bahkan mendapatkan cuplikan kode yang dihasilkan, sebaiknya gunakan Google AI Studio.

Membuat teks dari file gambar (enkode base64)

Sebelum mencoba contoh ini, selesaikan bagian Sebelum memulai dalam panduan ini untuk menyiapkan project dan aplikasi.
Di bagian tersebut, Anda juga akan mengklik tombol untuk penyedia Gemini API yang dipilih sehingga Anda melihat konten khusus penyedia di halaman ini.

Anda dapat meminta model Gemini untuk membuat teks dengan meminta teks dan gambar—memberikan setiap mimeType file input dan file itu sendiri. Temukan persyaratan dan rekomendasi untuk file input nanti di halaman ini.

Swift

Anda dapat memanggil generateContent() untuk membuat teks dari input multimodal teks dan gambar.

Input file tunggal


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

Input beberapa file


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.0-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

Anda dapat memanggil generateContent() untuk membuat teks dari input multimodal teks dan gambar.

Untuk Kotlin, metode dalam SDK ini adalah fungsi penangguhan dan perlu dipanggil dari Cakupan coroutine.

Input file tunggal


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

Input beberapa file

Untuk Kotlin, metode dalam SDK ini adalah fungsi penangguhan dan perlu dipanggil dari Cakupan 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-2.0-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

Anda dapat memanggil generateContent() untuk membuat teks dari input multimodal teks dan gambar.

Untuk Java, metode dalam SDK ini menampilkan ListenableFuture.

Input file tunggal


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

Input beberapa file


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

Anda dapat memanggil generateContent() untuk membuat teks dari input multimodal teks dan gambar.

Input file tunggal


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

Input beberapa file


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.0-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

Anda dapat memanggil generateContent() untuk membuat teks dari input multimodal teks dan gambar.

Input file tunggal


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

Input beberapa file


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.0-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

Anda dapat memanggil GenerateContentAsync() untuk membuat teks dari input multimodal teks dan gambar.

Input file tunggal


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

Input beberapa file


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

Pelajari cara memilih model yang sesuai untuk kasus penggunaan dan aplikasi Anda.

Menampilkan respons secara bertahap

Sebelum mencoba contoh ini, selesaikan bagian Sebelum memulai dalam panduan ini untuk menyiapkan project dan aplikasi.
Di bagian tersebut, Anda juga akan mengklik tombol untuk penyedia Gemini API yang dipilih sehingga Anda melihat konten khusus penyedia di halaman ini.

Anda dapat mencapai interaksi yang lebih cepat dengan tidak menunggu seluruh hasil dari pembuatan model, dan sebagai gantinya menggunakan streaming untuk menangani hasil sebagian. Untuk melakukan streaming respons, panggil generateContentStream.



Persyaratan dan rekomendasi untuk file gambar input

Perhatikan bahwa file yang diberikan sebagai data inline dienkode ke base64 saat dalam pengiriman, yang meningkatkan ukuran permintaan. Anda akan mendapatkan error HTTP 413 jika permintaan terlalu besar.

Lihat "File input dan persyaratan yang didukung untuk Vertex AI Gemini API" untuk mempelajari informasi mendetail tentang hal berikut:

Jenis MIME gambar yang didukung

Model multimodal Gemini mendukung jenis MIME gambar berikut:

Jenis MIME gambar Gemini 2.0 Flash Gemini 2.0 Flash‑Lite
PNG - image/png
JPEG - image/jpeg
WebP - image/webp

Batas per permintaan

Tidak ada batasan spesifik untuk jumlah piksel dalam gambar. Namun, gambar yang lebih besar akan diskalakan ke bawah dan diisi agar sesuai dengan resolusi maksimum 3072 x 3072 sekaligus mempertahankan rasio aspek aslinya.

Berikut adalah jumlah maksimum file gambar yang diizinkan dalam permintaan perintah:

  • Gemini 2.0 Flash dan Gemini 2.0 Flash‑Lite: 3.000 gambar



Kamu bisa apa lagi?

Mencoba kemampuan lain

Pelajari cara mengontrol pembuatan konten

Anda juga dapat bereksperimen dengan perintah dan konfigurasi model, bahkan mendapatkan cuplikan kode yang dihasilkan menggunakan Google AI Studio.

Pelajari lebih lanjut model yang didukung

Pelajari model yang tersedia untuk berbagai kasus penggunaan serta kuota dan harga-nya.


Berikan masukan tentang pengalaman Anda dengan Firebase AI Logic