Spring AI - Generate Image

Generate Image is a feature of the Spring AI project. It provides a simple and flexible way to generate images using AI models. The feature is designed to be easy to use and extend, allowing developers to quickly build and deploy image generation applications.

Maven Dependency

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<properties>
<java.version>17</java.version>
<spring-ai.version>1.0.0-M5</spring-ai.version>
</properties>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>${spring-ai.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-openai</artifactId>
</dependency>

Configuration

To use the Generate Image feature, you need to configure the OpenAI API key and the model to use for image generation. You can do this in your application.properties file.

1
2
spring.ai.openai.api-key=${OPENAI_API_KEY}
spring.ai.openai.image.options.model=dall-e-3

Generate Image with OpenAI

To generate an image using OpenAI, you can use the OpenAiImageModel provided by Spring AI. You can inject OpenAiImageModel into your service or controller and use it to generate images based on prompts.

1
2
3
4
5
6
7
private final OpenAiImageModel openAiImageModel;

ImageResponse imageResponse = openAiImageModel.call(
new ImagePrompt(prompt)
);

String imageUrl = imageResponse.getResult().getOutput().getUrl();

Generate Image with Options

1
2
3
4
5
6
7
8
9
ImageResponse imageResponse = openAiImageModel.call(
new ImagePrompt(prompt, OpenAiImageOptions.builder()
.width(1024)
.height(1024)
.style("vivid")
.build()
)
);
String imageUrl = imageResponse.getResult().getOutput().getUrl();

Returning Image in HTTP Response

You can return the generated image in an HTTP response by reading the image from the URL and writing it to the response output stream. Here is an example of how to do this in a Spring controller:

1
2
3
4
5
6
7
8
String imageUrl = imageResponse.getResult().getOutput().getUrl();

URL url = new URL(imageUrl);
BufferedImage image = ImageIO.read(url);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "png", baos);

return ResponseEntity.ok(baos.toByteArray());

Reference