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

springboot 上传图片 转存成webp

第一步先引入包

   <!-- webp-imageio 依赖 -->
        <dependency>
            <groupId>org.sejda.imageio</groupId>
            <artifactId>webp-imageio</artifactId>
            <version>0.1.6</version>
        </dependency>

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

 /**
     * 通用上传请求(单个)
     */
    @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 里面的方法了

  /**
     * 根据文件路径上传
     *
     * @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);
        }
    }
 /**
     * 文件上传
     *
     * @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);
        }
    }

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


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

相关文章:

  • 3.在Vue 3中使用Echarts实现水球效果
  • linux安装nginxs报错:openssl not found
  • 20241227在ubuntu20.04.6系统中,如何用watch命令每秒钟调用nvidia-smi来监控GPU
  • 【Spring】基于XML的Spring容器配置——Bean的作用域
  • Web开发:ORM框架之使用Freesql的分表分页写法
  • Android 设置铃声和闹钟
  • Docker--Kibana
  • MYSQL如何重置root密码
  • MYSQL使用角色
  • wx006基于springboot+vue+uniapp的电器维修系统小程序
  • uniapp下载打开实现方案,支持安卓ios和h5,下载文件到指定目录,安卓文件管理内可查看到
  • termux-boot安卓开机自动启动应用
  • Colyseus的room.onStateChange重复触发问题
  • Redis 集群架构:高可用与扩展性
  • 苍穹外卖day07缓存部分分析
  • 深入理解 Docker 网桥配置与网络管理
  • C#编写的金鱼趣味小应用 - 开源研究系列文章
  • 博通收购VMware后,新旧VMware兼容性列表查询方案对比
  • 未来网络技术的新征程:5G、物联网与边缘计算(10/10)
  • 【小程序】wxss与rpx单位以及全局样式和局部样式