Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Imagen è un modello di generazione di immagini. Può essere utilizzato per generare avatar personalizzati per i profili utente o per integrare asset visivi personalizzati nei flussi di schermate esistenti al fine di aumentare il coinvolgimento degli utenti.
Puoi accedere ai modelli Imagen dalla tua app per Android utilizzando l'SDK Firebase AI Logic. I modelli Imagen sono disponibili utilizzando entrambi i fornitori di API di Firebase AI Logic: l'API Gemini Developer (consigliata per la maggior parte degli sviluppatori) e Vertex AI.
Figura 1.
Accedi ai modelli Imagen utilizzando Firebase AI Logic.
Sperimenta con i prompt
Spesso sono necessari più tentativi per creare i prompt ideali. Puoi sperimentare con i prompt di immagini in Vertex AI Studio, un'IDE per la progettazione e la prototipazione dei prompt. Per suggerimenti su come migliorare i prompt, consulta la
guida agli attributi di prompt e immagine.
Figura 2.
Vertex AI Studio può aiutarti a perfezionare i prompt per la generazione di immagini.
Configura un progetto Firebase e connetti la tua app
Aggiungi le seguenti dipendenze al file build.gradle:
dependencies{// Import the BoM for the Firebase platformimplementation(platform("com.google.firebase:firebase-bom:34.2.0"))// Add the dependency for the Firebase AI Logic library. When using the BoM,// you don't specify versions in Firebase library dependenciesimplementation("com.google.firebase:firebase-ai")}
Genera un'immagine
Per generare un'immagine nella tua app per Android, inizia creando un'istanza di ImagenModel con una configurazione facoltativa.
Puoi utilizzare il parametro generationConfig per definire un prompt negativo, il numero di immagini, le proporzioni delle immagini di output, il formato dell'immagine e aggiungere una filigrana. Puoi utilizzare il parametro safetySettings per configurare i filtri di sicurezza
e delle persone.
Kotlin
valconfig=ImagenGenerationConfig{numberOfImages=2,aspectRatio=ImagenAspectRatio.LANDSCAPE_16x9,imageFormat=ImagenImageFormat.jpeg(compressionQuality=100),addWatermark=false}// Initialize the Gemini Developer API backend service// For Vertex AI use Firebase.ai(backend = GenerativeBackend.vertexAI())valmodel=Firebase.ai(backend=GenerativeBackend.googleAI()).imagenModel(modelName="imagen-3.0-generate-002",generationConfig=config,safetySettings=ImagenSafetySettings(safetyFilterLevel=ImagenSafetyFilterLevel.BLOCK_LOW_AND_ABOVE,personFilterLevel=ImagenPersonFilterLevel.BLOCK_ALL))
Java
ImagenGenerationConfigconfig=newImagenGenerationConfig.Builder().setNumberOfImages(2).setAspectRatio(ImagenAspectRatio.LANDSCAPE_16x9).setImageFormat(ImagenImageFormat.jpeg(100)).setAddWatermark(false).build();// For Vertex AI use Firebase.ai(backend = GenerativeBackend.vertexAI())ImagenModelFuturesmodel=ImagenModelFutures.from(FirebaseAI.ai(backend=GenerativeBackend.googleAI()).imagenModel("imagen-3.0-generate-002",config,ImagenSafetySettings.builder().setSafetyFilterLevel(ImagenSafetyFilterLevel.BLOCK_LOW_AND_ABOVE).setPersonFilterLevel(ImagenPersonFilterLevel.BLOCK_ALL).build()));
Una volta creato ImagenModel, puoi generare immagini chiamando
generateImages:
Kotlin
valimageResponse=model.generateImages(prompt="An astronaut riding a horse",)valimage=imageResponse.images.firstvalbitmapImage=image.asBitmap()
Java
CompletableFuture<GenerateContentResponse>futureResponse=model.generateContent(Content.newBuilder().addParts(Part.newBuilder().setText("An astronaut riding a horse").build()).build());try{GenerateContentResponseimageResponse=futureResponse.get();List<GeneratedImage>images=imageResponse.getCandidates(0).getContent().getParts(0).getInlineData().getImagesList();if(!images.isEmpty()){GeneratedImageimage=images.get(0);BitmapbitmapImage=image.asBitmap();// Use bitmapImage}}catch(ExecutionException|InterruptedExceptione){e.printStackTrace();}
I campioni di contenuti e codice in questa pagina sono soggetti alle licenze descritte nella Licenza per i contenuti. Java e OpenJDK sono marchi o marchi registrati di Oracle e/o delle sue società consociate.
Ultimo aggiornamento 2025-08-30 UTC.
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Mancano le informazioni di cui ho bisogno","missingTheInformationINeed","thumb-down"],["Troppo complicato/troppi passaggi","tooComplicatedTooManySteps","thumb-down"],["Obsoleti","outOfDate","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Problema relativo a esempi/codice","samplesCodeIssue","thumb-down"],["Altra","otherDown","thumb-down"]],["Ultimo aggiornamento 2025-08-30 UTC."],[],[],null,["Imagen is an image generation model. It can be used to generate\ncustom avatars for user profiles or to integrate personalized visual assets into\nexisting screen flows to increase user engagement.\n\nYou can access [Imagen models](https://firebase.google.com/docs/vertex-ai/models) from your Android app using the\n[Firebase AI Logic SDK.](https://firebase.google.com/docs/vertex-ai/generate-images-imagen?platform=android) Imagen models are available using both\nFirebase AI Logic [API providers](/ai/gemini#api-providers): Gemini Developer API (recommended for most\ndevelopers) and Vertex AI.\n**Figure 1.** Access Imagen models using Firebase AI Logic. **Note:** Firebase AI Logic doesn't yet support all the features available for the server-side integrations of Imagen models. Learn more about the supported capabilities in the [Firebase documentation](https://firebase.google.com/docs/vertex-ai/generate-images-imagen?platform=android#capabilities-features).\n\nExperiment with prompts\n\nCreating the ideal prompts often takes multiple attempts. You can experiment\nwith image prompts in [Vertex AI Studio](https://console.cloud.google.com/vertex-ai/generative/vision), an IDE for prompt\ndesign and prototyping. For tips on how to improve your prompts, review the\n[prompt and image attribute guide](https://cloud.google.com/vertex-ai/generative-ai/docs/image/img-gen-prompt-guide).\n**Figure 2.** Vertex AI Studio can help you refine your image generation prompts.\n\nSet up a Firebase project and connect your app\n\nFollow the steps in the Firebase documentation to\n[add Firebase to your Android project](https://firebase.google.com/docs/android/setup).\n\nAdd the Gradle dependency\n\nAdd the following dependencies to your `build.gradle` file: \n\n dependencies {\n // Import the BoM for the Firebase platform\n implementation(platform(\"com.google.firebase:firebase-bom:34.2.0\"))\n\n // Add the dependency for the Firebase AI Logic library. When using the BoM,\n // you don't specify versions in Firebase library dependencies\n implementation(\"com.google.firebase:firebase-ai\")\n }\n\nGenerate an image\n\nTo generate an image in your Android app, start by instantiating an\n`ImagenModel` with an optional configuration.\n\nYou can use the [`generationConfig`](https://firebase.google.com/docs/vertex-ai/model-parameters?platform=android) parameter to define a negative prompt, the\nnumber of images, the output image aspect ratio, the image format and add a\nwatermark. You can use the [`safetySettings`](https://firebase.google.com/docs/vertex-ai/safety-settings?platform=android) parameter to configure the safety\nand person filters.\n**Note:** Refer to the Firebase documentation for up-to-date information about [available Imagen models](https://firebase.google.com/docs/vertex-ai/models). \n\nKotlin \n\n val config = ImagenGenerationConfig {\n numberOfImages = 2,\n aspectRatio = ImagenAspectRatio.LANDSCAPE_16x9,\n imageFormat = ImagenImageFormat.jpeg(compressionQuality = 100),\n addWatermark = false\n }\n\n // Initialize the Gemini Developer API backend service\n // For Vertex AI use Firebase.ai(backend = GenerativeBackend.vertexAI())\n val model = Firebase.ai(backend = GenerativeBackend.googleAI()).imagenModel(\n modelName = \"imagen-3.0-generate-002\",\n generationConfig = config,\n safetySettings = ImagenSafetySettings(\n safetyFilterLevel = ImagenSafetyFilterLevel.BLOCK_LOW_AND_ABOVE,\n personFilterLevel = ImagenPersonFilterLevel.BLOCK_ALL\n )\n )\n\nJava \n\n ImagenGenerationConfig config = new ImagenGenerationConfig.Builder()\n .setNumberOfImages(2)\n .setAspectRatio(ImagenAspectRatio.LANDSCAPE_16x9)\n .setImageFormat(ImagenImageFormat.jpeg(100))\n .setAddWatermark(false)\n .build();\n\n // For Vertex AI use Firebase.ai(backend = GenerativeBackend.vertexAI())\n ImagenModelFutures model = ImagenModelFutures.from(\n FirebaseAI.ai(backend = GenerativeBackend.googleAI()).imagenModel(\n \"imagen-3.0-generate-002\",\n config,\n ImagenSafetySettings.builder()\n .setSafetyFilterLevel(ImagenSafetyFilterLevel.BLOCK_LOW_AND_ABOVE)\n .setPersonFilterLevel(ImagenPersonFilterLevel.BLOCK_ALL)\n .build())\n );\n\nOnce your `ImagenModel` is instantiated, you can generate images by calling\n`generateImages`: \n\nKotlin \n\n val imageResponse = model.generateImages(\n prompt = \"An astronaut riding a horse\",\n )\n val image = imageResponse.images.first\n val bitmapImage = image.asBitmap()\n\nJava \n\n CompletableFuture\u003cGenerateContentResponse\u003e futureResponse =\n model.generateContent(\n Content.newBuilder()\n .addParts(\n Part.newBuilder()\n .setText(\"An astronaut riding a horse\")\n .build())\n .build());\n\n try {\n GenerateContentResponse imageResponse = futureResponse.get();\n List\u003cGeneratedImage\u003e images =\n imageResponse\n .getCandidates(0)\n .getContent()\n .getParts(0)\n .getInlineData()\n .getImagesList();\n\n if (!images.isEmpty()) {\n GeneratedImage image = images.get(0);\n Bitmap bitmapImage = image.asBitmap();\n // Use bitmapImage\n }\n } catch (ExecutionException | InterruptedException e) {\n e.printStackTrace();\n }"]]