020-Spring AI Alibaba DashScope Image 功能完整案例 - 指南

本案例将引导您一步步构建一个 Spring Boot 应用,演示如何利用 Spring AI Alibaba 的 Image 模型功能,实现基于文本描述的图像生成。

1. 案例目标

我们将创建一个包含三个核心功能的 Web 应用:

  1. 基本图像生成 (/example/image):使用默认提示词生成一张图像。
  2. 多图像生成 (/example/image/multiPrompt):根据单个提示词生成多张图像。
  3. 多条件图像生成 (/example/image/multipleConditions):根据多个参数(主题、环境、高度、宽度、风格)生成定制化图像。

2. 技术栈与核心依赖

  • Spring Boot 3.x
  • Spring AI Alibaba (用于对接阿里云 DashScope 图像生成模型)
  • Maven (项目构建工具)

在 pom.xml 中,你需要引入以下核心依赖:


    
    
        com.alibaba.cloud.ai
        spring-ai-alibaba-starter-dashscope
        1.0.0-M2 
    
    
    
        org.springframework.boot
        spring-boot-starter-web
    



    
        
            org.springframework.boot
            spring-boot-dependencies
            3.3.1
            pom
            import
        
        
            com.alibaba.cloud
            spring-cloud-alibaba-dependencies
            2023.0.1.2
            pom
            import
        
    

3. 项目配置

在 src/main/resources/application.yml 文件中,配置你的 DashScope API Key。

server:
  port: 10008
spring:
  application:
    name: spring-ai-alibaba-dashscope-image-example
  ai:
    dashscope:
      api-key: ${AI_DASHSCOPE_API_KEY} # 建议使用环境变量,更安全

重要提示:请将 AI_DASHSCOPE_API_KEY 环境变量设置为你从阿里云获取的有效 API Key。你也可以直接将其写在配置文件中,但这不推荐用于生产环境。

4. 编写 Java 代码

4.1 DashScopeImageApplication.java

Spring Boot 应用程序的主类。

package com.alibaba.cloud.ai.example.image.dashscope;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DashScopeImageApplication {
    public static void main(String[] args) {
        SpringApplication.run(DashScopeImageApplication.class, args);
    }
}

4.2 DashScopeImageController.java

实现图像生成功能的控制器类。

package com.alibaba.cloud.ai.example.image.dashscope.controller;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.ai.image.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
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;
@RestController
@RequestMapping("/example")
public class DashScopeImageController {
    private final ImageModel imageModel;
    private static final String DEFAULT_PROMPT = "为人工智能生成一张富有科技感的图片!";
    public DashScopeImageController(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);
        }
    }
    /**
     * 生成多张图像
     */
    @GetMapping("/image/multiPrompt")
    public ResponseEntity> generateImageWithMultiPrompt(
            @RequestParam(value = "prompt", defaultValue = "一只会编程的猫") String prompt,
            @RequestParam(defaultValue = "2") int count) {
        ImageOptions options = ImageOptionsBuilder.builder()
                .N(count)
                .build();
        ImageResponse response = imageModel.call(new ImagePrompt(prompt, options));
        Set imageSet = response.getResults().stream().map(result -> result.getOutput().getUrl()).collect(Collectors.toSet());
        return ResponseEntity.ok(imageSet);
    }
    /**
     * 多条件图像生成
     */
    @GetMapping("/image/multipleConditions")
    public ResponseEntity multipleConditions(
            @RequestParam(value = "subject", defaultValue = "一只会编程的猫") String subject,
            @RequestParam(value = "environment", defaultValue = "办公室") String environment,
            @RequestParam(value = "height", defaultValue = "1024") Integer height,
            @RequestParam(value = "width", defaultValue = "1024") Integer width,
            @RequestParam(value = "style", defaultValue = "生动") String style) {
        String prompt = String.format(
                "一个%s,置身于%s的环境中,使用%s的艺术风格,高清4K画质,细节精致",
                subject, environment, style
        );
        ImageOptions options = ImageOptionsBuilder.builder()
                .height(height)
                .width(width)
                .build();
        try {
            ImageResponse response = imageModel.call(new ImagePrompt(prompt, options));
            return ResponseEntity.ok(response.getResult().getOutput().getUrl());
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of(
                            "error", "图像生成失败",
                            "message", e.getMessage(),
                            "timestamp", LocalDateTime.now()
                    ));
        }
    }
}

5. 运行与测试

  1. 启动应用:运行你的 Spring Boot 主程序。
  2. 使用浏览器或 API 工具(如 Postman, curl)进行测试

测试 1:基本图像生成

访问以下 URL,使用默认提示词生成一张图像。

http://localhost:10008/example/image

预期响应:直接返回一张 PNG 格式的图像。

测试 2:多图像生成

访问以下 URL,生成多张图像。

http://localhost:10008/example/image/multiPrompt?prompt=一只会编程的猫&count=2

预期响应:返回一个包含两个图像 URL 的集合。

[ "https://example.com/image1.png", "https://example.com/image2.png" ]

测试 3:多条件图像生成

访问以下 URL,使用多个参数生成定制化图像。

http://localhost:10008/example/image/multipleConditions?subject=一只会编程的猫&environment=办公室&height=1024&width=1024&style=生动

预期响应:返回生成的图像 URL。

"https://example.com/generated-image.png"

测试 4:错误处理

当图像生成失败时,系统会返回错误信息。

{ "error": "图像生成失败", "message": "具体错误信息", "timestamp": "2025-01-01T12:00:00" }

6. 实现思路与扩展建议

实现思路

本案例的核心思想是利用 Spring AI Alibaba 的 ImageModel 接口简化图像生成流程。通过这个接口,我们可以:

  • 简化 API 调用:无需直接与 DashScope API 交互,Spring AI Alibaba 封装了所有复杂性。
  • 灵活配置:通过 ImageOptions 可以轻松配置图像生成的各种参数。
  • 错误处理:内置的错误处理机制,使应用更加健壮。

扩展建议

  • 图像风格库:可以创建一个预定义的图像风格库,让用户通过简单的名称选择不同的风格。
  • 图像历史记录:添加数据库支持,保存用户生成的图像历史记录,方便后续查看和管理。
  • 异步处理:对于复杂的图像生成任务,可以实现异步处理,避免长时间阻塞用户请求。
  • 图像编辑功能:集成图像编辑功能,如裁剪、调整大小、添加滤镜等。
  • 用户认证与授权:添加用户认证机制,限制 API 使用频率,防止滥用。
  • 多模型支持:扩展应用以支持多个图像生成模型,让用户可以选择最适合的模型。
posted @ 2025-11-25 09:43  yangykaifa  阅读(41)  评论(0)    收藏  举报