Camel Components

Spring AI Image

Since Camel 4.19

Only producer is supported

The Spring AI Image component generates images from text prompts using any image model supported by Spring AI, including OpenAI DALL-E, Stability AI, and local models via Ollama.

Maven users will need to add the following dependency to their pom.xml:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-spring-ai-image</artifactId>
    <version>x.x.x</version>
</dependency>

URI format

spring-ai-image:imageId[?options]

Where imageId can be any string to uniquely identify the endpoint.

Configuring Options

Camel components are configured on two separate levels:

  • component level

  • endpoint level

Configuring Component Options

At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.

For example, a component may have security settings, credentials for authentication, urls for network connection and so forth.

Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.

You can configure components using:

  • the Component DSL.

  • in a configuration file (application.properties, *.yaml files, etc).

  • directly in the Java code.

Configuring Endpoint Options

You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.

Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.

A good practice when configuring options is to use Property Placeholders.

Property placeholders provide a few benefits:

  • They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.

  • They allow externalizing the configuration from the code.

  • They help the code to become more flexible and reusable.

The following two sections list all the options, firstly for the component followed by the endpoint.

Component Options

The Spring AI Image component supports the following options which are listed below.

Name Description Default Type

configuration (producer)

The configuration that each endpoint starts from. The options of an endpoint override it.

SpringAiImageConfiguration

height (producer)

The height of the image in pixels. The accepted sizes depend on the provider and the model. OpenAI uses the height only together with the width, as the size WIDTHxHEIGHT (such as 1024x1024).

Integer

imageModel (producer)

Autowired Required The Spring AI ImageModel that generates the images, such as OpenAiImageModel. When not set, the single ImageModel in the registry is used.

ImageModel

lazyStartProducer (producer)

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

model (producer)

The name of the model of the provider that generates the images, such as dall-e-3. When not set, the model of the default options of the ImageModel is used.

String

n (producer)

The number of images to generate. When the model returns more than one image, the message body is a List of Image. When not set, the ImageModel uses its default.

Integer

responseFormat (producer)

The format of the generated image: url (the Image has a URL to download the image from) or b64_json (the Image has the base64-encoded image data, which converts to byte[]). When not set, the provider default applies. Support depends on the provider and the model.

String

style (producer)

The style of the generated image, such as vivid or natural for the OpenAI dall-e-3 model. The accepted values depend on the provider and the model.

String

width (producer)

The width of the image in pixels. The accepted sizes depend on the provider and the model. OpenAI uses the width only together with the height, as the size WIDTHxHEIGHT (such as 1024x1024).

Integer

autowiredEnabled (advanced)

Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc.

true

boolean

Endpoint Options

The Spring AI Image endpoint is configured using URI syntax:

spring-ai-image:imageId

With the following path and query parameters:

Path Parameters

Name Description Default Type

imageId (producer)

Required Any name that identifies the endpoint. It is not sent to the image model.

String

Query Parameters

Name Description Default Type

height (producer)

The height of the image in pixels. The accepted sizes depend on the provider and the model. OpenAI uses the height only together with the width, as the size WIDTHxHEIGHT (such as 1024x1024).

Integer

imageModel (producer)

Autowired Required The Spring AI ImageModel that generates the images, such as OpenAiImageModel. When not set, the single ImageModel in the registry is used.

ImageModel

model (producer)

The name of the model of the provider that generates the images, such as dall-e-3. When not set, the model of the default options of the ImageModel is used.

String

n (producer)

The number of images to generate. When the model returns more than one image, the message body is a List of Image. When not set, the ImageModel uses its default.

Integer

responseFormat (producer)

The format of the generated image: url (the Image has a URL to download the image from) or b64_json (the Image has the base64-encoded image data, which converts to byte[]). When not set, the provider default applies. Support depends on the provider and the model.

String

style (producer)

The style of the generated image, such as vivid or natural for the OpenAI dall-e-3 model. The accepted values depend on the provider and the model.

String

width (producer)

The width of the image in pixels. The accepted sizes depend on the provider and the model. OpenAI uses the width only together with the height, as the size WIDTHxHEIGHT (such as 1024x1024).

Integer

lazyStartProducer (producer (advanced))

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

Message Headers

The Spring AI Image component supports the following message header(s), which is/are listed below:

Name Description Default Type

CamelSpringAiImageN (producer)

Constant: N

The number of images to generate. Overrides the n option; an ImagePrompt body that sets n wins over both.

Integer

CamelSpringAiImageWidth (producer)

Constant: WIDTH

The width of the image in pixels. Overrides the width option; an ImagePrompt body that sets the width wins over both.

Integer

CamelSpringAiImageHeight (producer)

Constant: HEIGHT

The height of the image in pixels. Overrides the height option; an ImagePrompt body that sets the height wins over both.

Integer

CamelSpringAiImageModel (producer)

Constant: MODEL

The name of the model of the provider that generates the images. Overrides the model option; an ImagePrompt body that sets the model wins over both.

String

CamelSpringAiImageResponseFormat (producer)

Constant: RESPONSE_FORMAT

The format of the generated image: url or b64_json. Overrides the responseFormat option; an ImagePrompt body that sets the response format wins over both.

String

CamelSpringAiImageStyle (producer)

Constant: STYLE

The style of the generated image, such as vivid or natural. Overrides the style option; an ImagePrompt body that sets the style wins over both.

String

CamelSpringAiImageResponseMetadata (producer)

Constant: RESPONSE_METADATA

The ImageResponseMetadata of the response, such as the creation time and, when the provider reports it, the usage.

ImageResponseMetadata

CamelSpringAiImageGeneration (producer)

Constant: IMAGE_GENERATION

The ImageGeneration when the model returns one image: the Image and its ImageGenerationMetadata (such as the revised prompt of OpenAI).

ImageGeneration

CamelSpringAiImageGenerations (producer)

Constant: IMAGE_GENERATIONS

The list of ImageGeneration when the model returns more than one image, in the order of the Image list in the message body.

List

Message Body

The message body at each side of the Spring AI Image component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.

Side Body Description

Producer input

any

The prompt as text, or an ImagePrompt. The options and headers fill the generic options the ImagePrompt leaves unset; provider options such as OpenAiImageOptions are used as is. Another body is converted to text, and no body fails.

Producer output

pojo or list

The generated org.springframework.ai.image.Image, with a URL or base64 data, or a List of Image when the model returns more than one (n above 1). An Image converts to byte[] by decoding the base64 data; an Image with only a URL fails to convert to byte[], so set responseFormat=b64_json to get the image data.

The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.

Usage

Configuring the ImageModel

The component requires a Spring AI ImageModel bean. When using Spring Boot with a Spring AI starter (e.g., spring-ai-starter-model-openai), the ImageModel bean is auto-configured.

Basic Image Generation

Send a text prompt as the message body to generate an image:

Java-only: Java lambda Processor with Spring AI Image API
from("direct:generate")
    .setBody(constant("A camel walking through the desert at sunset"))
    .to("spring-ai-image:gen?imageModel=#imageModel")
    .log("Generated image: ${body.getClass().getSimpleName()}")
    .process(exchange -> {
        Image image = exchange.getIn().getBody(Image.class);
        String base64Data = image.getB64Json();  // Base64-encoded image bytes
        String imageUrl = image.getUrl();         // URL (provider-dependent)
        log.info("Image base64 length: {}, URL: {}",
            base64Data != null ? base64Data.length() : "N/A", imageUrl);
    });

The response body is a org.springframework.ai.image.Image object containing either base64-encoded image data (b64Json) or a URL (url), depending on the provider and responseFormat setting.

The component includes built-in type converters that automatically convert Image objects to byte[] (by decoding the base64 data), InputStream, or String. This means downstream components like file: can consume the image directly without any intermediate processing.

Image Options

Control image generation parameters via endpoint configuration or headers. Headers override endpoint configuration at runtime.

Via Endpoint Configuration

Java-only: Java string concatenation in URI
from("direct:generate")
    .to("spring-ai-image:gen?imageModel=#imageModel"
        + "&model=dall-e-3"
        + "&width=512&height=512"
        + "&responseFormat=b64_json"
        + "&style=vivid");

Via Headers

Java-only: Java test API (ProducerTemplate with lambda)
Exchange exchange = template.request("direct:generate", e -> {
    e.getIn().setBody("A red apple on a white table");
    e.getIn().setHeader(SpringAiImageHeaders.WIDTH, 256);
    e.getIn().setHeader(SpringAiImageHeaders.HEIGHT, 256);
    e.getIn().setHeader(SpringAiImageHeaders.MODEL, "dall-e-3");
    e.getIn().setHeader(SpringAiImageHeaders.RESPONSE_FORMAT, "b64_json");
});

With an ImagePrompt body

When the message body is an org.springframework.ai.image.ImagePrompt, the options it sets win, and the endpoint options and headers fill the options it leaves unset (n, width, height, model, responseFormat and style). This applies to the generic options of a prompt (new ImagePrompt(text) or options from ImageOptionsBuilder). The options of a provider, such as OpenAiImageOptions, are used as is, as a generic copy of them would lose the provider settings (for example the OpenAI quality).

Java-only: Java Spring AI SDK API
// the options of the prompt win per option: the prompt width (1024) overrides the endpoint width (512),
// and the height the prompt leaves unset falls back to the endpoint height (512)
ImagePrompt prompt = new ImagePrompt("A red apple on a white table",
    ImageOptionsBuilder.builder().width(1024).build());
template.sendBody("spring-ai-image:gen?imageModel=#imageModel&width=512&height=512", prompt);

Saving Images to Files

The component includes a built-in TypeConverter that automatically converts Image objects to byte[]. This means you can pipe generated images directly to the file: component without any intermediate processing:

  • Java

  • XML

  • YAML

// Generate and save — no processor needed
from("direct:generate")
    .to("spring-ai-image:gen?imageModel=#imageModel&width=512&height=512")
    .to("file:output?fileName=generated.png");
<route>
    <from uri="direct:generate"/>
    <to uri="spring-ai-image:gen?imageModel=#imageModel&amp;width=512&amp;height=512"/>
    <to uri="file:output?fileName=generated.png"/>
</route>
- route:
    from:
      uri: direct:generate
      steps:
        - to:
            uri: spring-ai-image:gen
            parameters:
              imageModel: "#imageModel"
              width: 512
              height: 512
        - to:
            uri: file:output?fileName=generated.png

The Image → byte[] conversion decodes the base64 data automatically. Set responseFormat=b64_json when the provider returns a URL by default: the URL is not downloaded, so an Image with only a URL fails to convert to byte[] or InputStream, and the route fails instead of writing the URL text into the file.

Using with Ollama (Local Image Generation)

Ollama supports image generation models via its OpenAI-compatible API. Configure the Spring AI OpenAI ImageModel to point at Ollama. Since Spring AI 2.0 the OpenAI models are built on the official openai-java SDK, so the Ollama URL is set on the SDK client:

Java-only: Java Spring AI SDK configuration
OpenAIClient openAiClient = new OpenAIClientImpl(
    ClientOptions.builder()
        .httpClient(SpringAiOpenAiHttpClient.builder().build())
        .baseUrl("http://localhost:11434/v1")
        .apiKey("unused")
        .build());

OpenAiImageOptions defaultOptions = OpenAiImageOptions.builder()
    .model("x/flux2-klein:4b")
    .build();

ImageModel imageModel = OpenAiImageModel.builder()
    .openAiClient(openAiClient)
    .options(defaultOptions)
    .build();

Then use the Camel endpoint to control resolution:

  • Java

  • XML

  • YAML

from("direct:generate")
    .to("spring-ai-image:gen?imageModel=#imageModel&width=512&height=512")
    .to("file:output?fileName=camel-image.png");
<route>
    <from uri="direct:generate"/>
    <to uri="spring-ai-image:gen?imageModel=#imageModel&amp;width=512&amp;height=512"/>
    <to uri="file:output?fileName=camel-image.png"/>
</route>
- route:
    from:
      uri: direct:generate
      steps:
        - to:
            uri: spring-ai-image:gen
            parameters:
              imageModel: "#imageModel"
              width: 512
              height: 512
        - to:
            uri: file:output?fileName=camel-image.png

Multiple Image Generation

Set the n parameter to generate multiple images. When n > 1, the body contains a List<Image> instead of a single Image:

Java-only: Java test API (ProducerTemplate)
from("direct:batch")
    .to("spring-ai-image:gen?imageModel=#imageModel&n=3");

// Usage:
List<Image> images = template.requestBody("direct:batch",
    "A camel in different art styles", List.class);

Type Converters

The component registers automatic type converters for Image objects:

From To Behavior

Image

byte[]

Decodes base64 data. An Image with only a URL fails to convert, as the image is not downloaded: set responseFormat=b64_json

Image

InputStream

Wraps the byte[] above in ByteArrayInputStream

Image

String

Returns base64 string or URL