Spring AI文生图(Text-to-Image)入门示例

本文通过一个hello world简单示例演示,如何基于Spring Boot集成Spring AI开源框架,快速集成调用阿里云的百炼大模型AI服务,验证AI大模型“文生图”的功能。

在Spring AI框架中,文生图(Text-to-Image)功能允许开发者通过文本描述自动生成图像。这一特性依赖于预训练的生成模型,这些模型能够根据给定的文本提示创建视觉内容。为了实现这一目标,Spring AI提供了相应的接口和类来简化与这些模型的交互过程。

1、使用Spring AI 前提条件

2、创建SpringBoot工程

通过IDEA开发工具,创建一个普通的Java工程,注意JDK版本至少是17以上,我这里使用的是jdk21版本。

3、配置pom.xml文件

工程创建完成后,在pom.xml里添加依赖。

首先,需要在项目中添加 spring-boot-starter-parent声明,指定springboot框架的版本号:

<parent>

     <groupId>org.springframework.boot</groupId>

     <artifactId>spring-boot-starter-parent</artifactId>

     <version>3.3.3</version>

     <relativePath/>

</parent>

在dependencies标签中引入spring-boot-starter-web和spring-ai-alibaba-starter依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>

  <groupId>com.alibaba.cloud.ai</groupId>

  <artifactId>spring-ai-alibaba-starter</artifactId>

  <version>1.0.0-M3.3</version>

</dependency>

由于 spring-ai 相关依赖包还没有发布到中央仓库,如出现 spring-ai-core 等相关依赖解析问题,请在您项目的 pom.xml 依赖中加入如下仓库配置。

<repositories>

  <repository>

    <id>spring-milestones</id>

    <name>Spring Milestones</name>

    <url>https://repo.spring.io/milestone</url>

    <snapshots>

      <enabled>false</enabled>

    </snapshots>

  </repository>

</repositories>

最后pom.xml文件完整内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.yuncheng</groupId>
    <artifactId>spring-ai-helloworld</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>21</maven.compiler.source>
        <maven.compiler.target>21</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.3.3</version>
        <relativePath/>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud.ai</groupId>
            <artifactId>spring-ai-alibaba-starter</artifactId>
            <version>1.0.0-M3.3</version>
        </dependency>
    </dependencies>

    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

</project>

4、配置yml文件

在工程的resources目录下的application-dev.yml文件里增加如下配置:

注意:api-key要替换成自己从阿里百炼平台申请的key

server:
  port: 8080

spring:
  application:
    name: spring-ai-helloworld
  ai:
    dashscope:
      api-key: sk-b90ad31bb3eb4a1585251928356d39dc5

5、创建ImageController

Spring AI框架的ImageModel API 抽象了应用程序通过模型调用实现“文生图”的交互过程,即应用程序接收文本,调用模型生成图片。ImageModel 的入参为包装类型ImagePrompt,输出类型为ImageResponse。

package com.yuncheng;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.ai.image.*;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/ai")
public class ImageController {
    private final ImageModel imageModel;
    private static final String DEFAULT_PROMPT = "为人工智能生成一张富有科技感的图片!";

    public ImageController(ImageModel imageModel) {
        this.imageModel = imageModel;
    }

    @GetMapping("/image")
    public void image(HttpServletResponse response) {

        ImageResponse imageResponse = imageModel.call(new ImagePrompt(DEFAULT_PROMPT));
        String imageUrl = imageResponse.getResult().getOutput().getUrl();

        try {
            URL url = URI.create(imageUrl).toURL();
            InputStream in = url.openStream();

            response.setHeader("Content-Type", MediaType.IMAGE_PNG_VALUE);
            response.getOutputStream().write(in.readAllBytes());
            response.getOutputStream().flush();
        } catch (IOException e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

}

本示例使用了spring ai alibaba开源框架,spring-ai-alibaba-starter AutoConfiguration 默认初始化了 ImageModel 实例,我们可以选择直接注入并使用默认实例。

6、创建Application启动类

package com.yuncheng;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;

@SpringBootApplication
public class AiApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext application = SpringApplication.run(AiApplication.class, args);
        Environment env = application.getEnvironment();
        String port = env.getProperty("server.port");
        System.out.println("AiApplication启动成功,服务端口为:" + port);

    }
}

7、启动Springboot工程并测试

工程启动成功后,把下面地址输入到浏览器里,验证AI大模型文生图:

http://localhost:8080/ai/image

浏览器显示:

8、总结

通过上述介绍可以看出,Spring AI框架中的文生图功能及其相关接口设计旨在为开发者提供便捷且强大的工具,用于探索和应用最新的图像生成技术。而ImageModel类则扮演着连接具体模型与应用程序逻辑的重要桥梁角色,帮助用户轻松集成并利用各种先进的图像生成能力。

1)Spring AI文生图接口使用

  • Spring AI为文生图功能设计了直观易用的API接口,使得开发者可以通过简单的调用来生成图像。
  • 通常情况下,这类接口会接受一个或多个文本提示作为输入,并返回生成的图像数据或者图像文件的URL链接。

2)ImageModel 类的使用

ImageModel 类是Spring AI框架中用于表示图像生成模型的核心组件之一。它的主要职责包括但不限于:

  • 封装模型信息:存储有关特定图像生成模型的关键元数据,例如模型名称、版本号、支持的输入格式等。
  • 管理模型加载:负责初始化并加载预训练的图像生成模型到内存中,以便后续可以高效地进行推理操作。
  • 定义推理逻辑:提供标准化的方法来执行基于文本提示的图像生成任务,确保不同模型之间的行为一致性。
  • 处理输出结果:将模型生成的原始图像数据转换为易于使用的格式,如JPEG、PNG等,并可能附加额外的元信息(如生成时间戳、所用模型ID等)。

猜你喜欢

转载自blog.csdn.net/wxz258/article/details/145278109
今日推荐