springboot上传图片并且压缩到项目资源目录下

本文介绍了如何在SpringBoot应用中实现图片上传,并将上传的图片进行压缩后保存到项目的资源目录下,详细讲解了相关配置和代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

   public Resp addImage(MultipartFile file) {
        //获取项目classess/static的地址
        String staticPath = ClassUtils.getDefaultClassLoader().getResource("static").getPath();
        Map<String, String> imgInfo = new HashMap<String, String>();
        if (file != null) {
            //获取图片的名称
            String oldName = file.getOriginalFilename();
            //随机生成数字来作为图片的前缀加上图片的格式jpg/png
            String newName = randomNum() + oldName.substring(oldName.lastIndexOf("."));
            //图片保存路径
            String savePath = staticPath + File.separator + "imgGallery";
            File folder = new File(savePath);
            //没有文件夹imgGallery就创建
            if (!folder.exists()) {
                folder.mkdirs();
            }
            try {
                //压缩图片再保存outputQuality(1f) 越接近1,图片质量越高
                Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(1f).outputFormat("jpg").toFile(new File(folder,newName));
                //直接保存
                //file.transferTo(new File(folder, newName));
                //获取保存的图片
                String imgUrl = ResourceUtils.getURL("classpath:").getPath() + "static/imgGallery/" + newName;
                imgInfo.put("imgUrl", imgUrl);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return Resp.ok("上传成功").put("imgInfo", imgInfo);
        }
        return Resp.error("上传失败");

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值