{"id":5184,"date":"2024-08-29T07:16:18","date_gmt":"2024-08-29T07:16:18","guid":{"rendered":"https:\/\/www.aegissofttech.com\/insights\/?p=5184"},"modified":"2025-10-07T10:42:58","modified_gmt":"2025-10-07T10:42:58","slug":"generate-images-from-text-with-springai","status":"publish","type":"post","link":"https:\/\/www.aegissofttech.com\/insights\/generate-images-from-text-with-springai\/","title":{"rendered":"How to Generate Images from Text with SpringAI"},"content":{"rendered":"<p>With technology, artificial intelligence (AI) integration in applications has become innovative and efficient. The <a href=\"https:\/\/spring.io\/projects\/spring-ai\" target=\"_blank\" rel=\"noopener\">Spring AI Project<\/a> is an influential add-on framework based on Spring, making it easy to bring AI capabilities to Spring-based applications. <a href=\"https:\/\/www.aegissofttech.com\/java-application-development-services.html\">Java application development services<\/a>\u00a0have embraced this trend, leveraging AI to enhance application functionality and user experiences. In this article, we take a brief look at Spring AI and guide you through creating an image from a user prompt.<\/p>\n<h2>1. What is Spring AI?<\/h2>\n<p>The <a href=\"https:\/\/spring.io\/projects\/spring-ai\" target=\"_blank\" rel=\"noopener\">Spring AI Project<\/a> was an extension project to the Spring framework where additional capabilities in the form of tools and libraries that assist in the integration of AI into <a href=\"https:\/\/www.aegissofttech.com\/java\/spring-development-services.html\">Spring boot application development <\/a>were introduced. It connects AI models with end-user programs ensuring easy use and maximum flexibility and offers rich support for many AI services and frameworks. Whether one is working with machine learning models, natural language processing, or computer vision, the Spring AI will help embed all the other AI capabilities into applications in the most effortless manner possible.<\/p>\n<h2>2. How to generate an OpenAI API key?<\/h2>\n<p>We will now understand how to obtain an OpenAI key. We&#8217;ll use an OpenAI model to generate an image.<\/p>\n<ul>\n<li>Create an Account or Sign In: Go to the <a href=\"https:\/\/www.openai.com\" target=\"_blank\" rel=\"noopener\">OpenAI website<\/a> and either sign up for a new account or log in to your existing one.<\/li>\n<li>Access API Keys: After logging in, head to the API Keys section within your account dashboard.<\/li>\n<li>Generate a New API Key: Select the option to create a new API key. Assign a name or description to the key for easy reference.<\/li>\n<li>Generate and Save the Key: Click the Generate Key button. Make sure to copy the newly created API key and store it in a safe place, as you will need it to access OpenAI&#8217;s services.<\/li>\n<\/ul>\n<h2>3. Code example<\/h2>\n<h3>3.1 Dependencies<\/h3>\n<p>Add the following dependencies to your <code>build.grade<\/code> file.<\/p>\n<pre>plugins {\n    id 'org.springframework.boot' version '3.2.4'\n    id 'io.spring.dependency-management' version '1.1.3'\n    id 'java'\n}\ngroup = 'com.spring.ai.imageclient'\nversion = '0.0.1-SNAPSHOT'\nrepositories {\n    mavenCentral()\n    maven {\n        url 'https:\/\/repo.spring.io\/milestone'\n    }\n}\ndependencyManagement {\n    imports {\n        mavenBom \"org.springframework.ai:spring-ai-bom:0.8.1\"\n    }\n}\ndependencies {\n    implementation 'org.springframework.boot:spring-boot-starter-web'\n    implementation 'org.springframework.ai:spring-ai-openai-spring-boot-starter'\n    testImplementation 'org.springframework.boot:spring-boot-starter-test'\n}\next {\n    set('springAiVersion', \"0.8.1\")\n}\ntasks.withType(Test) {\n    useJUnitPlatform()\n}\n<\/pre>\n<h3>3.2 Update the application properties<\/h3>\n<p>Add the following properties to the <code>application.properties<\/code> file. Remember to replace the OpenAI key.<\/p>\n<pre># application properties\nspring.application.name=spring-ai-image-generation\nserver.port=8080\nspring.main.banner-mode=off\n# OpenAI API Key\nspring.ai.openai.api-key=your_openai_api_key\n<\/pre>\n<h3>3.3 Create a configuration<\/h3>\n<p>Create a configuration class to map the OpenAI key to the Image Client. The OpenAI key&#8217;s value will be read from the properties file and injected using Spring&#8217;s <code>@Value<\/code> annotation.<\/p>\n<pre>package com.spring.ai.imageclient.configuration;\nimport org.springframework.ai.image.ImageClient;\nimport org.springframework.ai.openai.OpenAiImageClient;\nimport org.springframework.ai.openai.api.OpenAiImageApi;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\n@Configuration\npublic class OpenAIConfig {\n    @Bean\n    public ImageClient imageClient(@Value(\"${spring.ai.openai.api-key}\") String apiKey) {\n        System.out.println(\"API Key: \" + apiKey);\n        System.out.println(\"Creating OpenAI Image Client\");\n        return new OpenAiImageClient(new OpenAiImageApi(apiKey));\n    }\n}\n<\/pre>\n<h3>3.4 Creating the Controller<\/h3>\n<p>The <code>ImageGenerationController<\/code> class is a REST controller in a Spring Boot application, responsible for handling HTTP requests related to <a href=\"https:\/\/www.quarule.com\/how-use-novelai-image-generation-free\/\" target=\"_blank\" rel=\"noopener\"><strong>image generation<\/strong><\/a>. The <code>PromptRequest<\/code> and <code>PromptResponse<\/code> are the DTO classes to map the request and response.<\/p>\n<pre>package com.spring.ai.imageclient.controller;\nimport com.spring.ai.imageclient.dto.PromptRequest;\nimport com.spring.ai.imageclient.dto.PromptResponse;\nimport org.apache.commons.lang3.StringUtils;\nimport org.springframework.ai.image.Image;\nimport org.springframework.ai.image.ImageClient;\nimport org.springframework.ai.image.ImagePrompt;\nimport org.springframework.ai.openai.OpenAiImageClient;\nimport org.springframework.ai.openai.OpenAiImageOptions;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.web.bind.annotation.PostMapping;\nimport org.springframework.web.bind.annotation.RequestBody;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RestController;\n@RestController\n@RequestMapping(\"\/api\/v1\/image\")\npublic class ImageGenerationController {\n    private final ImageClient imageClient;\n    \/\/ constructor injection\n    @Autowired\n    public ImageGenerationController(OpenAiImageClient openAiImageClient) {\n        this.imageClient = openAiImageClient;\n    }\n    \/*\n     * Generate an image based on the prompt\n     * @param request - prompt request\n     * @return prompt response\n     *\/\n    @PostMapping(\"\/generate\")\n    public PromptResponse getImage(@RequestBody PromptRequest request) {\n        final String prompt = request.getPrompt();\n        \/\/ input validation\n        if (StringUtils.isEmpty(prompt)) {\n            System.out.println(\"Prompt is required\");\n            throw new IllegalArgumentException(\"Prompt is required\");\n        }\n        System.out.println(\"Prompt: \" + prompt);\n        System.out.println(\"Generating image...\");\n        \/\/ image options\n        OpenAiImageOptions imageOptions = OpenAiImageOptions.builder()\n                .withQuality(\"standard\")\n                .withHeight(1024)\n                .withN(1)\n                .withWidth(1792)\n                .build();\n        \/\/ image prompt\n        ImagePrompt imagePrompt = new ImagePrompt(prompt, imageOptions);\n        System.out.println(\"Calling image client...\");\n        \/\/ class ep\n        Image img = imageClient.call(imagePrompt).getResult().getOutput();\n        System.out.println(\"Image generated successfully\");\n        return new PromptResponse(img.getUrl());\n    }\n}\n<\/pre>\n<h3>3.5 Create the Main file<\/h3>\n<p>Create a Spring Boot application to initialize the application.<\/p>\n<pre>package com.spring.ai.imageclient;\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n@SpringBootApplication\npublic class DemoApplication {\n    public static void main(String[] args) {\n        SpringApplication.run(DemoApplication.class, args);\n        System.out.println(\"App started successfully\");\n    }\n}\n<\/pre>\n<h3>3.6 Run the application and Demo<\/h3>\n<p>Now start the application and open the Postman tool to hit the api endpoint. Import the below curl POST request in the Postman tool. Remember to change the prompt with a valid instruction.<\/p>\n<pre>curl 'http:\/\/localhost:8080\/api\/v1\/image\/generate' -H 'Content-Type: application\/json' -d '{\n    \"prompt\": \"a white punk lion with futuristic background\"\n}'\n<\/pre>\n<p>If everything goes well the response containing the image url will be returned from OpenAI and sent to the client as a JSON response.<\/p>\n<pre>{\n  \"generatedUrl\": \"https:\/\/oaidalleapiprodscus.blob.core.windows.net\/private\/org-9Ys0ZRqaTWzWMNLv1XefTZvC\/user-YJ5pfUPFbA4XmjGWBKadjply\/img-nHbvdQQAgcu39Fi2APtj3yO2.png?st=2024-08-25T02%3A34%3A58Z&amp;se=2024-08-25T04%3A34%3A58Z&amp;sp=r&amp;sv=2024-08-04&amp;sr=b&amp;rscd=inline&amp;rsct=image\/png&amp;skoid=d505667d-d6c1-4a0a-bac7-5c84a87759f8&amp;sktid=a48cca56-e6da-484e-a814-9c849652bcb3&amp;skt=2024-08-24T23%3A11%3A39Z&amp;ske=2024-08-25T23%3A11%3A39Z&amp;sks=b&amp;skv=2024-08-04&amp;sig=Zz4PHhKvcGlu4F28yFg1aa\/qX6f3%2BYpqM7eMJW\/Y54U%3D\"\n}\n<\/pre>\n<p>\/\/ Fig. 1: Demo image<\/p>\n<p><img fetchpriority=\"high\" decoding=\"async\" src=\"https:\/\/www.aegissofttech.com\/insights\/wp-content\/uploads\/2025\/01\/springai-generateimagefromtext-demooutput-1.png\" alt=\"springai-generate image from text-demo output\" width=\"457\" height=\"261\" title=\"\"><\/p>\n<blockquote><p>Continue exploring Spring Boot by checking out our next blog:<br \/>\n<strong><a href=\"https:\/\/www.aegissofttech.com\/insights\/alternatives-to-spring-apache-shiro-2-quarkus\/\">Alternatives to Spring Boot<\/a><\/strong><\/p><\/blockquote>\n<h2>4. Conclusion<\/h2>\n<p>In conclusion, as AI continues to reshape the technological landscape, tools like Spring AI are essential for seamlessly integrating AI into applications. By leveraging Spring AI, <a href=\"https:\/\/www.aegissofttech.com\/hire-spring-boot-developers.html\">Spring developers<\/a> can easily add advanced AI capabilities to their Spring-based projects, enabling innovative solutions like generating images from user prompts.<\/p>\n<h2>5. Download the code<\/h2>\n<p>You can download the full code here: <a href=\"https:\/\/www.aegissofttech.com\/insights\/wp-content\/uploads\/2024\/08\/springaiimagegeneration.zip\"><strong>Download<\/strong><\/a><\/p>\n<blockquote><p>For more insights on\u00a0Kafka migration to Spring Boot, don\u2019t miss our next blog:\u00a0<a href=\"https:\/\/www.aegissofttech.com\/insights\/kafka-baggage-amp-webflux-migration-to-spring-boot\/\">Kafka migration to Spring Boot 3.X<\/a><\/p><\/blockquote>\n<p><strong>Read More:<\/strong><\/p>\n<ul>\n<li><a href=\"https:\/\/www.aegissofttech.com\/insights\/how-to-create-ghibli-style-ai-art-with-gpt-4o\/\" target=\"_blank\" rel=\"noopener\">How to Create Ghibli-Style AI Art with GPT-4o<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":" ","protected":false},"author":12,"featured_media":5186,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[12,919],"tags":[917,918],"class_list":["post-5184","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","category-spring-boot","tag-images-from-text","tag-springai"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.aegissofttech.com\/insights\/wp-json\/wp\/v2\/posts\/5184","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.aegissofttech.com\/insights\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.aegissofttech.com\/insights\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.aegissofttech.com\/insights\/wp-json\/wp\/v2\/users\/12"}],"replies":[{"embeddable":true,"href":"https:\/\/www.aegissofttech.com\/insights\/wp-json\/wp\/v2\/comments?post=5184"}],"version-history":[{"count":56,"href":"https:\/\/www.aegissofttech.com\/insights\/wp-json\/wp\/v2\/posts\/5184\/revisions"}],"predecessor-version":[{"id":15139,"href":"https:\/\/www.aegissofttech.com\/insights\/wp-json\/wp\/v2\/posts\/5184\/revisions\/15139"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.aegissofttech.com\/insights\/wp-json\/wp\/v2\/media\/5186"}],"wp:attachment":[{"href":"https:\/\/www.aegissofttech.com\/insights\/wp-json\/wp\/v2\/media?parent=5184"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.aegissofttech.com\/insights\/wp-json\/wp\/v2\/categories?post=5184"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.aegissofttech.com\/insights\/wp-json\/wp\/v2\/tags?post=5184"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}