07.Spring AI 接入智谱文生图:从配置到实战

一、背景与目标

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();
    }
}
相关推荐
潜鳞~10 分钟前
智能体 Agent-RAG实现原理-有理有据的回答问题!
人工智能
秋天的怀念_David19 分钟前
算法一千零一夜 · 第四十夜 · 错层的状态码
java·程序人生·算法
xyphf_和派孔明20 分钟前
第九章: 上下文工程五大策略与六大模块交叉矩阵纵览
java·开发语言
水如烟28 分钟前
孤能子视角:LeCun团队的“柏拉图式推理”——锚点、映射与两张量表的正交
人工智能
码上观世界29 分钟前
不用会唱,借助AI也能有一版“自己唱的歌”
人工智能·音乐变声
三掌柜66629 分钟前
国产大模型开始卷效率了,阶跃 Step 5 实测
人工智能
Zzj_tju33 分钟前
总体分数之外,问答错误集中在哪里?
人工智能·深度学习·语言模型·自然语言处理
清如许.36 分钟前
语音智能体如何在通话过程中检测并切换用户的语言?
人工智能·大模型·llm
宿州派大星36 分钟前
构建 AI 课堂分析系统:从讯飞 ASR 到 Qwen 大模型全流程实战(附避坑指南)
人工智能