Spring AI: ImageClient

Introduction to ImageClient

The ImageClient in Spring AI is a powerful tool that allows you to interact with AI models to generate, manipulate, and analyze images. This tutorial will guide you through setting up a Spring Boot application and demonstrate how to use ImageClient to handle AI-generated images effectively.

1. Setting Up the Project

Step 1: Create a New Spring Boot Project

You can create a new Spring Boot project using Spring Initializr or your preferred IDE. Ensure you include the necessary dependencies for Spring Web and Spring AI.

Using Spring Initializr:

  • Go to start.spring.io
  • Select:
    • Project: Maven Project
    • Language: Java
    • Spring Boot: 3.0.0 (or latest)
    • Dependencies: Spring Web, Spring AI
  • Generate the project and unzip it.

Step 2: Add spring-ai-openai-spring-boot-starter Dependency

In your project's pom.xml, add the following dependency:

<dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-openai-spring-boot-starter</artifactId> <version>1.0.0</version> </dependency> 

2. Configuring the Spring Boot Starter

Step 1: Add API Key to Configuration

Create a application.properties or application.yml file in your src/main/resources directory and add your OpenAI API key.

For application.properties:

openai.api.key=your_openai_api_key 

For application.yml:

openai: api: key: your_openai_api_key 

Step 2: Create a Configuration Class

Create a new configuration class to set up the OpenAI client and the ImageClient abstraction.

package com.example.demo.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.ai.openai.OpenAiClient; import org.springframework.ai.openai.ImageClient; import org.springframework.ai.openai.OpenAiImageClient; @Configuration public class OpenAiConfig { @Bean public OpenAiClient openAiClient() { return new OpenAiClient(); } @Bean public ImageClient imageClient(OpenAiClient openAiClient) { return new OpenAiImageClient(openAiClient); } } 

3. Implementing the ImageClient

Step 1: Create a Service for Image Operations

Create a service class that will handle interactions with the ImageClient abstraction.

package com.example.demo.service; import org.springframework.ai.openai.ImageClient; import org.springframework.ai.openai.model.ImageRequest; import org.springframework.ai.openai.model.ImageResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class ImageService { @Autowired private ImageClient imageClient; public String generateImage(String prompt) { ImageRequest request = new ImageRequest(); request.setPrompt(prompt); request.setSize("1024x1024"); ImageResponse response = imageClient.generateImage(request); return response.getImageUrl(); } } 

Step 2: Create a Controller for the Service

Create a controller to expose an endpoint for generating images.

package com.example.demo.controller; import com.example.demo.service.ImageService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class ImageController { @Autowired private ImageService imageService; @GetMapping("/generateImage") public String generateImage(@RequestParam String prompt) { return imageService.generateImage(prompt); } } 

4. Creating a Simple Frontend

For demonstration purposes, we will create a simple HTML page that allows users to interact with the ImageClient.

Step 1: Create an HTML File

Create an index.html file in the src/main/resources/static directory.

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>AI Image Generator</title> </head> <body> <h1>AI Image Generator</h1> <div> <textarea id="prompt" rows="4" cols="50" placeholder="Type your image prompt here..."></textarea><br> <button onclick="generateImage()">Generate</button> </div> <div id="imageResult"></div> <script> function generateImage() { const prompt = document.getElementById('prompt').value; fetch(`/generateImage?prompt=${encodeURIComponent(prompt)}`) .then(response => response.text()) .then(data => { const img = document.createElement('img'); img.src = data; img.alt = 'Generated Image'; document.getElementById('imageResult').appendChild(img); }); } </script> </body> </html> 

5. Testing the Integration

Step 1: Run the Application

Run your Spring Boot application. Ensure the application starts without errors.

Step 2: Access the Image Generator

Open your browser and navigate to http://localhost:8080. You should see the simple image generator interface. Type a prompt and click "Generate" to see the AI-generated image.

Conclusion

In this tutorial, you learned how to set up and use the ImageClient feature in a Spring Boot application with Spring AI. You created a service to handle image generation, a controller to expose an endpoint, and a simple frontend for user interaction. This setup provides a foundation for building more complex and feature-rich AI image applications. 

Explore further customization and enhancements to create a robust image client.


Comments