当前位置: 首页 > article >正文

Spring AI Alibaba ImageModel使用

一、ImageModel简介

1、Image Model

ImageModel API 抽象了应用程序通过模型调用实现“文生图”的交互过程,即应用程序接收文本,调用模型生成图片。

ImageModel 的入参为包装类型 ImagePrompt,输出类型为 ImageResponse。

二、ImageModel使用

Spring AI Alibaba对话模型(Chat Model):https://java2ai.com/docs/1.0.0-M5.1/tutorials/chat-model/

Spring AI Alibaba 支持Model 抽象与通义系列模型的适配,并通过 spring-ai-alibaba-starter AutoConfiguration 自动初始化了默认实例,因此我们可以在应用程序中直接注入 ChatModel、ImageModel 等 bean,当然在需要的时候也可以自定义 Model 实例。

在这里插入图片描述

1、编写 Controller接口

在普通 Controller Bean 中注入 ImageModel 实例,实现“文生图”功能:

  • 简单调用
  • 自定义 LLMs ImageOptions 参数调用
@Slf4j
@RestController
@RequestMapping("/dashscope/image-model")
public class DashScopeImageController {

    private static final String DEFAULT_PROMPT = "为人工智能生成一张富有科技感的图片!";

    private final ImageModel imageModel;

    /**
     * 使用如下的方式自动注入 ImageModel
     *
     * @param imageModel
     */
    public DashScopeImageController(ImageModel imageModel) {
        this.imageModel = imageModel;
    }

    /**
     * 简单调用
     */
    @GetMapping("/simple/image")
    public void simpleImage(HttpServletResponse response, String userInputPrompt) {
        if (StringUtils.isBlank(userInputPrompt)) {
            userInputPrompt = DEFAULT_PROMPT;
        }

        // 默认使用的是 wanx-v1模型
        ImageResponse imageResponse = imageModel.call(new ImagePrompt(userInputPrompt));
        Image image = imageResponse.getResult().getOutput();

        // 获取图片的 URL。
        String imageUrl = image.getUrl();
        // 获取图片的 Base64 编码
        String b64Json = image.getB64Json(); 

        log.info(" simpleImage --> userInputPrompt = {}, imageUrl = {}", userInputPrompt, imageUrl);
        log.info(" simpleImage --> userInputPrompt = {}, b64Json = {}", userInputPrompt, b64Json);

        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);
        }
    }

    /**
     * 使用编程方式自定义 LLMs ImageOptions 参数,
     * {@link com.alibaba.cloud.ai.dashscope.image.DashScopeImageOptions}
     * 优先级高于在 application.yml 中配置的 LLMs 参数!
     */
    @GetMapping("/customOptions/image")
    public List<String> customOptionsImage(String userInputPrompt) {
        if (StringUtils.isBlank(userInputPrompt)) {
            userInputPrompt = DEFAULT_PROMPT;
        }

        // 自定义 LLMs ImageOptions 参数
        DashScopeImageOptions customOptions = DashScopeImageOptions.builder()
                // 默认使用的是 wanx-v1模型
                .withWidth(1024)
                .withHeight(1024)
                .withN(2) // 生成图片的数量
                .build();

        ImageResponse imageResponse = imageModel.call(new ImagePrompt(userInputPrompt, customOptions));
        List<ImageGeneration> imageGenerationList = imageResponse.getResults();

        List<String> imageUrlList = new ArrayList<>();
        for (ImageGeneration imageGeneration : imageGenerationList) {
            Image image = imageGeneration.getOutput();
            // 获取图片的 URL
            String imageUrl = image.getUrl();
            // 获取图片的 Base64 编码
            //String b64Json = image.getB64Json();

            log.info(" customOptionsImage --> userInputPrompt = {}, imageUrl = {}", userInputPrompt, imageUrl);
            imageUrlList.add(imageUrl);
        }
        return imageUrlList;
    }

}

启动项目,访问接口与 AI 大模型智能对话。

在这里插入图片描述
在这里插入图片描述

注意: dashscope 文生图返回的 图片url是有过期时间的(有效期一天),我们及时下载下来。

田园茶叶特写提示词:
超写实摄影风格,云南深山古树茶园清晨场景,苍劲虬曲的茶树特写,嫩绿茶叶上挂满晶莹露珠,晨光穿透薄雾洒在叶片上,茶农身着靛蓝布衣、头戴斗笠采摘茶叶,竹篓中堆满新鲜茶芽,背景是云雾缭绕的梯田与远山,色彩以翠绿、乳白、深褐为主,晨光暖金色点缀,画面宁静充满田园诗意,突出茶叶天然品质与手工采摘的传统感。

在这里插入图片描述

– 求知若饥,虚心若愚。


http://www.kler.cn/a/611081.html

相关文章:

  • 需求导向的K8S网络原理分析:Kube-proxy、Flannel、Calico的地位和作用
  • 浏览器存储 IndexedDB
  • CentOS 8 安装 Redis 全流程指南:从基础部署到远程安全配置
  • 无线安灯按钮盒汽车零部件工厂的故障告警与人员调度专家
  • 创建一个服务器启动自动执行的脚本,设置默认路由
  • 【MinIO】可靠的分布式MinIO集群部署
  • 基于深度学习的相位调制算法步骤
  • Android UI 组件系列(三):ImageView 使用技巧与图像加载
  • Unity游戏开发如何优化移动端的延迟渲染管线?
  • python笔记之判断月份有多少天
  • Rust从入门到精通之精通篇:24.高级异步编程
  • 做一个有天有地的css及html画的旋转阴阳鱼
  • Leetcode 188 买卖股票的最佳时机 Ⅳ
  • 【计算机网络】DHCP工作原理
  • Postman 如何发送 XML 格式的 API 请求?
  • 【redis】主从复制:单点问题、配置详解、特点详解
  • 使用 Vite 提升前端开发体验:入门与配置指南
  • 【云馨AI-大模型】自动化部署Dify 1.1.2,无需科学上网,Linux环境轻松实现,附Docker离线安装等
  • JVM类文件结构详解
  • 六级词汇量积累(day12)