springboot 上传图片 转存成webp

第一步先引入包

bash 复制代码
   <!-- webp-imageio 依赖 -->
        <dependency>
            <groupId>org.sejda.imageio</groupId>
            <artifactId>webp-imageio</artifactId>
            <version>0.1.6</version>
        </dependency>

下面就是上传的时候处理的了

bash 复制代码
 /**
     * 通用上传请求(单个)
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

下面是 uploadPath 里面的方法了

bash 复制代码
  /**
     * 根据文件路径上传
     *
     * @param baseDir 相对应用的基目录
     * @param file 上传的文件
     * @return 文件名称
     * @throws IOException
     */
    public static final String upload(String baseDir, MultipartFile file) throws IOException
    {
        try
        {
            return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
        }
        catch (Exception e)
        {
            throw new IOException(e.getMessage(), e);
        }
    }
bash 复制代码
 /**
     * 文件上传
     *
     * @param baseDir 相对应用的基目录
     * @param file 上传的文件
     * @param allowedExtension 上传文件类型
     * @return 返回上传成功的文件名
     * @throws FileSizeLimitExceededException 如果超出最大大小
     * @throws FileNameLengthLimitExceededException 文件名太长
     * @throws IOException 比如读写文件出错时
     * @throws InvalidExtensionException 文件校验异常
     */
    public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension)
            throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException,
            InvalidExtensionException
    {
        int fileNamelength = Objects.requireNonNull(file.getOriginalFilename()).length();
        if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH)
        {
            throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
        }

        assertAllowed(file, allowedExtension);

        String extension = getExtension(file);
        boolean isImage = isAllowedExtension(extension, MimeTypeUtils.IMAGE_EXTENSION);

        String fileName = extractFilename(file);
        String newExtension = isImage ? "webp" : extension; // 如果是图片,使用webp格式
        fileName = fileName.substring(0, fileName.lastIndexOf(".")) + "." + newExtension;

        String absPath = getAbsoluteFile(baseDir, fileName).getAbsolutePath();
        if (isImage) {
            // 将图片转换为webp格式
            jpg2webp(file, Paths.get(absPath).toString());
        } else {
            // 非图片文件,直接写入
            file.transferTo(Paths.get(absPath));
        }
        return getPathFileName(baseDir, fileName);
    }

    public static void jpg2webp(MultipartFile file, String newfilePath) throws IOException {
        try (InputStream is = file.getInputStream();
             FileImageOutputStream os = new FileImageOutputStream(new File(newfilePath))) {
            BufferedImage image = ImageIO.read(is);
            ImageWriter writer = ImageIO.getImageWritersByMIMEType("image/webp").next();
            if (writer == null) {
                throw new IOException("No writer found for WebP format");
            }
            WebPWriteParam writeParam = new WebPWriteParam(writer.getLocale());
            writeParam.setCompressionMode(WebPWriteParam.MODE_DEFAULT);
            writer.setOutput(os);
            writer.write(null, new IIOImage(image, null, null), writeParam);
            writer.dispose();
        } catch (IOException e) {
            throw new IOException("Error converting image to WebP format", e);
        }
    }

我是在若依框架弄的,详细代码可以下载若依然后加入这些代码就可以了

相关推荐
红橙Darren1 小时前
手写操作系统 - 环境搭建
android·微信·操作系统
_一条咸鱼_1 小时前
Android Runtime直接内存管理原理深度剖析(73)
android·面试·android jetpack
你听得到111 小时前
揭秘Flutter图片编辑器核心技术:从状态驱动架构到高保真图像处理
android·前端·flutter
wilinz1 小时前
Flutter Android 端接入百度地图踩坑记录
android·flutter
congvee1 小时前
springboot 学习第1期 - 创建工程
spring boot
风流 少年2 小时前
Cursor创建Spring Boot项目
java·spring boot·后端
毕设源码_钟学姐2 小时前
计算机毕业设计springboot宿舍管理信息系统 基于Spring Boot的高校宿舍管理平台设计与实现 Spring Boot框架下的宿舍管理系统开发
spring boot·后端·课程设计
军军君013 小时前
基于Springboot+UniApp+Ai实现模拟面试小工具二:后端项目搭建
前端·javascript·spring boot·spring·微信小程序·前端框架·集成学习
全栈凯哥3 小时前
16.Spring Boot 国际化完全指南
java·spring boot·后端
小袁拒绝摆烂4 小时前
SQL开窗函数
android·sql·性能优化