Welcome to the third lesson of our course on building an image generation service in Java! In our previous lessons, we created the PromptManager to format user inputs into detailed prompts and the ImageManager to handle storing and processing generated images. Now, we're ready to build the core component that brings everything together: the ImageGeneratorService.
The ImageGeneratorService is the central piece of our application that will:
- Connect to Google's
Gemini APIto generate images. - Use our
PromptManagerto format user inputs into effective prompts. - Pass the selected aspect ratio through to the prompt template.
- Store generated images using our
ImageManager. - Provide access to all previously generated images.
This service acts as the bridge between our application's components and the external AI service that actually creates the images. By encapsulating all the image generation logic in a dedicated service class, we maintain a clean separation of concerns in our application architecture.
In this lesson, we'll implement this service step by step, from setting up the client to handling responses and errors. By the end, you'll have a fully functional image generation service that you can later integrate into a Java web application.
Before we can generate images, we need to set up a way to communicate with Google's Gemini API. We'll use the Gemini Java SDK to call the generateContent flow with the gemini-3.1-flash-image model.
To do this, you'll need the following dependencies in your project:
These libraries let us call the API through the SDK and work with typed response objects instead of building raw HTTP requests by hand.
Next, let's create our ImageGeneratorService class and set up the service configuration in the constructor. In Java, you would typically place this class in a package such as com.codesignal.services and save it in a file named ImageGeneratorService.java:
In this constructor, we're doing several important things:
- Creating an instance of our
ImageManagerclass to handle storing and retrieving images. - Reading the
Gemini APIkey and baseURLfrom environment variables. - Building a
GeminiSDKclient that we can reuse for image generation requests.
In Java, environment variables can be accessed using System.getenv("VARIABLE_NAME"). This approach keeps sensitive information like API keys out of your source code.
Now that we have our service configuration set up, let's implement the core method of our service: generateImage(). This method will take a userInput string and an aspectRatio string, format them into a detailed prompt using our PromptManager, call the Gemini API through the SDK, and store the resulting image using our ImageManager.
Here is the implementation:
Let's break down what's happening in this method:
- We call
PromptManager.formatPrompt(userInput, aspectRatio)to convert the user's input into a detailedpromptusing our predefined template. - We build the request to the
Gemini APIusing thegemini-3.1-flash-imagemodel. - We set
responseModalitiesto["IMAGE"]so the model returns image content. - We inspect the returned
candidates[0].content.partslist and look for a part that includesinlineData, which is where the generated image bytes are returned. - We decode the returned image data from
Base64into raw bytes. - We pass the
promptandimageBytesto ourImageManager'saddImage()method, which stores the image and returns the Base64 string.
The method returns the Base64-encoded image data, which can be used directly in web applications.
Generating images through an external API can fail for various reasons: network issues, API limits, invalid prompts, or server errors. To make our service robust, we include checks for missing image data and throw clear exceptions when needed.
There are also Gemini-specific failure cases to be aware of. The generateContent response may return successfully but not include an image inlineData part — for example, if the model returns only text or if the content was filtered. Our code handles this explicitly by checking whether imageBytes is still null after iterating through all parts, and throwing a RuntimeException with a clear message in that case.
Now, let's add one more method to our service to retrieve all previously generated images:
This simple method delegates to our ImageManager's getImages() method, returning the complete list of stored images along with their associated prompts and IDs.
With these two methods, our ImageGeneratorService provides a complete interface for generating and retrieving images. The service integrates our previously built components (PromptManager and ImageManager) and connects them to the external Gemini API using the Gemini Java SDK.
Now that we've implemented our ImageGeneratorService, let's create a test class to verify that it works correctly. You can do this with a simple main method in a Java class, such as Main.java:
In this test code, we:
- Import our
ImageGeneratorServiceclass. - Define a sample
userInputandaspectRatiofor testing. - Create an instance of our
ImageGeneratorService. - Call the
generateImage()method with our sample input. - Print the result.
- Retrieve and print all stored images.
When running this code with a valid API key and the correct dependencies, you would see output similar to:
The Base64 string would be much longer in a real application, but it has been truncated here for readability. This string represents the encoded image data returned by the Gemini API in the inlineData.data field.
In this lesson, we've built the ImageGeneratorService, the core component of our image generation application. This service connects our previously built components (PromptManager and ImageManager) to Google's Gemini API using the Gemini Java SDK, calling the official generateContent flow with the gemini-3.1-flash-image model to generate high-quality images from text prompts.
Let's review what we've learned:
- We set up the
GeminiJava SDKto communicate with Google'sgenerateContentAPIinJava. - We implemented the
generateImage()method, calling thegenerateContentflow with thegemini-3.1-flash-imagemodel and configuring image output viaresponseModalities. - We passed the selected
aspectRatiothrough the prompt formatting step. - We parsed the
Geminiresponse by navigating tocandidates[0].content.partsand extracting the image bytes from theinlineData.datafield. - We added robust error handling to deal with potential
APIissues. - We created a method to retrieve all previously generated images.
- We tested our service with a sample prompt.
The ImageGeneratorService is a crucial piece of our application architecture. It encapsulates all the logic related to image generation, providing a clean interface for other components to use. In the next lesson, we'll build a controller that will use this service to handle HTTP requests in our Java web application.
In the upcoming practice exercises, you'll have the opportunity to work with the ImageGeneratorService, testing its functionality with different prompts and exploring how it integrates with the rest of our application. You'll also get to experiment with error handling and see how the service behaves in various scenarios.
Remember that to use this service in a real application, you'll need to:
- Add the
Gemini Java SDKdependency to yourJavaproject. - Obtain a valid
APIkey from Google. - Set the
GEMINI_API_KEYenvironment variable to yourAPIkey andGEMINI_BASE_URLto the appropriate Gemini endpoint.
With the ImageGeneratorService in place, we're one step closer to having a complete image generation web application!
