Integrating Text into Images with Gemini's Imagen and Java

Introduction to Text Integration in Image Generation

Welcome to the final lesson of this course on creating images with the Gemini API using Java. In previous lessons, you explored various aspects of image generation, including crafting effective prompts and using photography modifiers. Now, we will focus on integrating text into your images, a powerful feature that enhances the visual storytelling of your creations. Text integration allows you to add meaningful context or branding elements to your images, making them more engaging and informative.

In this lesson, you will learn how to construct prompts that guide the AI to place text within images effectively. We will also cover how to generate these images using gemini-3.1-flash-image in Java. By the end of this lesson, you will be equipped to create images with text that can be used for various applications, such as logos, posters, or digital art.

Constructing Effective Prompts for Text Placement

Creating effective prompts is crucial for guiding the AI to generate images with text. When constructing prompts, consider the following guidelines:

  • Character Limits: Keep text short, ideally 25 characters or fewer, to ensure clarity and readability.
  • Multiple Phrases: Use up to three distinct phrases to provide additional information without cluttering the image.
  • Text Placement: Specify where you want the text to appear, such as 'at the top arc' or 'at the bottom arc'.

Let's break down an example prompt:

"A circular emblem featuring a central image of a mountain. At the top arc, the text 'Adventure Awaits' is curved gracefully, and at the bottom arc, the text 'Explore the Unknown' follows the curve. The design has a vintage aesthetic with serif fonts."

This prompt provides clear guidance on text placement and style, helping the AI generate an image that meets your expectations.

Generating Images with Text Using Gemini

Now that you understand how to construct prompts, let's generate an image with text using the Gemini API in Java. Here is a step-by-step walkthrough of the code using the Gemini Java SDK and the gemini-3.1-flash-image model:

package com.codesignal;

import com.google.genai.Client;
import com.google.genai.types.Blob;
import com.google.genai.types.HttpOptions;
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.Part;


import java.io.FileOutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.List;

public class Main {
    public static void main(String[] args) throws Exception {
        String apiKey = System.getenv("GEMINI_API_KEY");
        String baseUrl = System.getenv("GEMINI_BASE_URL");

        Client client = new Client.Builder()
                .apiKey(apiKey)
                .httpOptions(HttpOptions.builder().baseUrl(baseUrl).apiVersion("v1beta").build())
                .build();

        // Define the prompt with text placement guidance
        String prompt = "A circular emblem featuring a central image of a mountain. "
                + "At the top arc, the text 'Adventure Awaits' is curved gracefully, "
                + "and at the bottom arc, the text 'Explore the Unknown' follows the curve. "
                + "The design has a vintage aesthetic with serif fonts.";

        GenerateContentResponse response = client.models.generateContent(
                "gemini-3.1-flash-image",
                prompt,
                GenerateContentConfig.builder()
                        .responseModalities(List.of("IMAGE"))
                        .build()
        );

        for (Part part : response.candidates().get().get(0).content().get().parts().get()) {
            if (part.inlineData().isPresent()) {
                byte[] imageBytes = Base64.getDecoder().decode(part.inlineData().get().data().orElseThrow(() -> new RuntimeException("No data found")));

                String outputDir = "public/images";
                Files.createDirectories(Paths.get(outputDir));
                String outputPath = outputDir + "/output-image.jpg";
                try (FileOutputStream fos = new FileOutputStream(outputPath)) {
                    fos.write(imageBytes);
                }
                System.out.println("Image written to: " + outputPath);
            }
        }
    }
}

In this code, you:

  • Retrieve the apiKey from environment variables and build a Client instance.
  • Construct a GenerateContentConfig that sets responseModalities to ["TEXT", "IMAGE"], telling the model to return image data alongside any text.
  • Call generateContent with the gemini-3.1-flash-image model and your prompt.
  • Iterate over the response parts and check for inlineData, which carries the Base64-encoded image bytes.
  • Decode the Base64 image data and save it as a file to disk.
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal