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

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是有过期时间的(有效期一天),我们及时下载下来。

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

在这里插入图片描述

– 求知若饥,虚心若愚。

相关文章:

  • vue的项目添加全局接口请求封装,并通过配置文件使接口请求变得更简洁易用
  • 13.2 kubelet containerRuntime接口定义和初始化
  • Java操作RabbitMQ
  • BCC-应用程序组件分析
  • 【身份安全】零信任安全框架梳理(一)
  • 如何在 Postman 中导入和导出 cURL 命令?
  • 用C/C++实现针对整数的BoomFilter
  • 解决Vmware 运行虚拟机Ubuntu22.04卡顿、终端打字延迟问题
  • 【每日论文】MetaSpatial: Reinforcing 3D Spatial Reasoning in VLMs for the Metaverse
  • 聊聊spring ai的mcp server
  • 基于gork的三端互联海陆空学习方案
  • Android 中 Activity 和 Fragment 的区别
  • Linux设置SSH免密码密钥登录
  • 使用AI一步一步实现若依(27)
  • Docker Compose 部署 Loki
  • SpringCloud Stream:消息驱动的微服务架构设计
  • LLM推理加速框架有哪些
  • 【江协科技STM32】读写备份寄存器RTC实时时钟(学习笔记)
  • Python电影市场特征:AR模型时间序列趋势预测、热图可视化评分影响分析IMDb数据|附数据代码
  • 低空智能目标(无人机)管理控制系统技术详解
  • 从咖啡节到话剧、演唱会,上海虹口“文旅商体展”联动促消费
  • “上报集团文化助力区域高质量发展赋能平台”揭牌
  • 龚正会见委内瑞拉副总统罗德里格斯
  • 日韩 “打头阵”与美国贸易谈判,汽车、半导体产业忧虑重重
  • 外交部:欢迎外国朋友“五一”来中国
  • 第二艘国产大型邮轮爱达·花城号完成坞内起浮