一、背景与目标
Spring AI 是 Spring 官方推出的 AI 应用开发框架,提供了统一的模型抽象层,让开发者可以用一致的方式接入不同厂商的大模型能力。除了对话、嵌入等常见能力外,Spring AI 也支持图像生成(Image Generation)场景。
智谱 AI(Zhipu AI)的 CogView 系列模型提供了文生图能力,通过标准的 HTTP 接口对外提供服务。本文将介绍如何在 Spring Boot 项目中借助 Spring AI 的 ImageModel 抽象,接入智谱文生图接口,完成从配置到实际调用的完整流程。
本文的目标是:
- 理解 Spring AI 图像生成的核心抽象与调用方式;
- 掌握智谱文生图接口的请求与响应结构;
- 完成一个可运行的 Spring Boot 示例,能够根据提示词生成图片并保存到本地。
二、环境与依赖准备
开始之前,请确认本地环境满足以下条件:
- JDK 17 及以上版本;
- Maven 3.8+ 或 Gradle 7+;
- Spring Boot 3.2+;
- 已注册智谱开放平台账号,并获取 API Key。
在智谱开放平台控制台创建 API Key 后,请妥善保存,后续通过配置文件注入,不要硬编码到代码中。
在 pom.xml 中引入 Spring AI 相关依赖。这里以 Spring AI 的 BOM 统一管理版本:
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>
<parent>
<groupId>com.erbao</groupId>
<artifactId>SpringAI</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>ImageModels</artifactId>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-zhipuai</artifactId>
</dependency>
</dependencies>
</project>
三、代码案例
配置
java
spring.application.name=SpringAIImage
server.port=8080
#使用 智普AI Embedding 模型,需要在pom.xml中引入对应依赖
spring.ai.zhipuai.api-key=aae0e......4f91f83.qk0D6n......W70
spring.ai.zhipuai.base-url=https://open.bigmodel.cn/api/paas
spring.ai.zhipuai.image.options.model=CogView-4
#使用 智普AI Chat 模型,需要在pom.xml中引入对应依赖
spring.ai.zhipuai.chat.options.model=GLM-4.7-Flash
接口
java
package com.erbao.rest;
import com.erbao.service.ImageService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.ai.image.Image;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
@RestController
@RequestMapping("/image")
public class ImageController {
@Autowired
private ImageService svc;
@GetMapping("/generate")
public void genRedirect(
@RequestParam(value = "message", defaultValue = "画一只小狗") String message,
HttpServletResponse response
) throws IOException {
System.out.println("请求参数prompt="+message);
Image image = svc.generateImage(message);
String url = image.getUrl();
if (url == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND, "图片生成失败");
return;
}
URL imageUrl = new URL(url);
URLConnection conn = imageUrl.openConnection();
String contentType = conn.getContentType();
response.setContentType(contentType != null ? contentType : "image/png");
response.setHeader("Content-Disposition", "inline");
try (InputStream is = conn.getInputStream();
var os = response.getOutputStream()) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
}
}
}
service
java
package com.erbao.service;
import org.springframework.ai.image.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ImageService {
@Autowired
private ImageModel imageModel;
public Image generateImage(String prompt) {
ImageOptions options = ImageOptionsBuilder.builder()
//.model("cogview-3")
.N(1) // 生成的图片数量
.width(512) // 图片宽度
.height(512)// 图片高度
.build();
// 创建 ImagePrompt 对象,用于封装本次图像生成请求
ImagePrompt imagePrompt = new ImagePrompt(
java.util.List.of(new org.springframework.ai.image.ImageMessage(prompt)),
options
);
//调用 ZhiPuAiImageModel 的 call() 方法,传入 ImagePrompt
ImageResponse resp = imageModel.call(imagePrompt);
System.out.println("返回图片信息"+resp.getResult().getOutput());
return resp.getResult().getOutput();
}
}