Analizowanie plików graficznych za pomocą interfejsu Gemini API

Możesz poprosić model Gemini o analizę plików graficznych, które podasz w treści (zakodowane w formacie base64) lub za pomocą adresu URL. Gdy używasz Firebase AI Logic, możesz wysłać to żądanie bezpośrednio z aplikacji.

Dzięki tej funkcji możesz m.in.:

  • tworzyć podpisy lub odpowiadać na pytania dotyczące obrazów,
  • pisać krótkie opowiadania lub wiersze o obrazach,
  • wykrywać obiekty na obrazie i zwracać ich współrzędne w ramce ograniczającej,
  • etykietować lub kategoryzować zbiór obrazów pod kątem nastroju, stylu lub innej cechy.

Przejdź do przykładowych fragmentów kodu

Przejdź do kodu odpowiedzi przesyłanych strumieniowo


Więcej opcji pracy z obrazami znajdziesz w innych przewodnikach
Generowanie danych wyjściowych w uporządkowanej formie Czat wieloetapowy Analizowanie obrazów na urządzeniu Generowanie obrazów

Zanim zaczniesz

Kliknij swojego dostawcę Gemini API, aby wyświetlić na tej stronie treści i kod specyficzne dla dostawcy.

Jeśli jeszcze tego nie zrobisz, zapoznaj się z przewodnikiem dla początkujących, w którym opisujemy, jak skonfigurować projekt Firebase, połączyć aplikację z Firebase, dodać pakiet SDK, zainicjować usługę backendu dla wybranego dostawcy Gemini API i utworzyć instancję GenerativeModel.

Do testowania i iteracji promptów zalecamy używanie Google AI Studio.

Generowanie tekstu na podstawie plików graficznych (zakodowanych w formacie base64)

Zanim wypróbujesz ten przykład, zapoznaj się z sekcją Zanim zaczniesz w tym przewodniku aby skonfigurować projekt i aplikację.
W tej sekcji klikniesz też przycisk dostawcy interfejsu Gemini API API, aby na tej stronie wyświetlały się treści specyficzne dla dostawcy.

Możesz poprosić model Gemini o wygenerowanie tekstu, podając tekst i obrazy – podając mimeType każdego pliku wejściowego i sam plik. Wymagania i zalecenia dotyczące plików wejściowych znajdziesz dalej na tej stronie.

Swift

Aby wygenerować tekst na podstawie multimodalnych danych wejściowych (tekstu i obrazów), możesz wywołać funkcję generateContent().

Dane wejściowe z jednego pliku


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

Dane wejściowe z wielu plików


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

Aby wygenerować tekst na podstawie multimodalnych danych wejściowych (tekstu i obrazów), możesz wywołać funkcję generateContent().

W przypadku języka Kotlin metody w tym pakiecie SDK są funkcjami zawieszającymi i muszą być wywoływane w zakresie współprogramu.

Dane wejściowe z jednego pliku


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

Dane wejściowe z wielu plików

W przypadku języka Kotlin metody w tym pakiecie SDK są funkcjami zawieszającymi i muszą być wywoływane w zakresie współprogramu.

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

Aby wygenerować tekst na podstawie multimodalnych danych wejściowych (tekstu i obrazów), możesz wywołać funkcję generateContent().

W przypadku języka Java metody w tym pakiecie SDK zwracają wartość ListenableFuture.

Dane wejściowe z jednego pliku


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

Dane wejściowe z wielu plików


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

Aby wygenerować tekst na podstawie multimodalnych danych wejściowych (tekstu i obrazów), możesz wywołać funkcję generateContent().

Dane wejściowe z jednego pliku


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

Dane wejściowe z wielu plików


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

Aby wygenerować tekst na podstawie multimodalnych danych wejściowych (tekstu i obrazów), możesz wywołać funkcję generateContent().

Dane wejściowe z jednego pliku


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

Dane wejściowe z wielu plików


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

Aby wygenerować tekst na podstawie multimodalnych danych wejściowych (tekstu i obrazów), możesz wywołać funkcję GenerateContentAsync().

Dane wejściowe z jednego pliku


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

Dane wejściowe z wielu plików


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

Dowiedz się, jak wybrać model odpowiednią dla Twojego przypadku użycia i aplikacji.

Przesyłanie odpowiedzi strumieniowo

Zanim wypróbujesz ten przykład, zapoznaj się z sekcją Zanim zaczniesz w tym przewodniku aby skonfigurować projekt i aplikację.
W tej sekcji klikniesz też przycisk dostawcy interfejsu Gemini API API, aby na tej stronie wyświetlały się treści specyficzne dla dostawcy.

Możesz przyspieszyć interakcje, nie czekając na cały wynik wygenerowany przez model, i zamiast tego użyć przesyłania strumieniowego do obsługi częściowych wyników. Aby przesyłać odpowiedź strumieniowo, wywołaj funkcję generateContentStream.



Wymagania i zalecenia dotyczące wejściowych plików graficznych

Pamiętaj, że plik podany jako dane w treści jest w trakcie przesyłania kodowany w formacie base64, co zwiększa rozmiar żądania. Jeśli żądanie jest zbyt duże, otrzymasz błąd HTTP 413.

Szczegółowe informacje o tych kwestiach znajdziesz na stronie „Obsługiwane pliki wejściowe i wymagania”:

Obsługiwane typy MIME obrazów

Gemini modele multimodalne obsługują te typy MIME obrazów:

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

Limity na żądanie

Nie ma konkretnego limitu liczby pikseli na obraz. Większe obrazy są jednak zmniejszane i uzupełniane, aby pasowały do maksymalnej rozdzielczości 3072 x 3072, przy zachowaniu oryginalnych proporcji.

Maksymalna liczba plików na żądanie: 3000 plików graficznych



Co jeszcze możesz zrobić?

Wypróbuj inne funkcje

Dowiedz się, jak kontrolować generowanie treści

Możesz też eksperymentować z promptami i konfiguracjami modeli, a nawet uzyskać wygenerowany fragment kodu za pomocą Google AI Studio.

Więcej informacji o obsługiwanych modelach

Dowiedz się więcej o modelach dostępnych w różnych przypadkach użycia oraz o ich limitach i cenach.


Prześlij opinię o korzystaniu z Firebase AI Logic