springMVC上传图片并压缩

今天IPad客户端突然找到我说IPad界面加载图片时内存暴增,需要我把图片压缩一下,在看了一些博客之后决定用谷歌的Thumbnailator,为啥?

压缩像素可调节、一行代码、压缩快,废话不多说来看看实现方式:

1、添加maven依赖

<dependency>
    <groupId>net.coobird</groupId>
    <artifactId>thumbnailator</artifactId>
    <version>0.4.8</version>
</dependency>


2、压缩代码

private Map<String, Object> saveFileAndThumbnail(MultipartFile file) throws BusinessException {  
        // 判断文件是否为空  
        if (!file.isEmpty()) {
            String root = fileUploadPath;
            String picturePath = "我是保存路径啊哈哈哈哈";
            String ext = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String newName = new Date().getTime()+ext;
            File filedict = new File(root+picturePath);
            if(!filedict.exists()){
                filedict.mkdirs();
            }
            File targetFile=new File(root+picturePath+File.separator+newName);
            File newFile=new File(root+picturePath+File.separator+"s"+newName);
            try {
                
                file.transferTo(targetFile);
                Thumbnails.of(targetFile)
                .scale(0.1f)//指定图片大小    0-1f  1f是原图
                .outputQuality(1f)//图片质量  0-1f  1f是原图
                .toFile(newFile);
                BufferedImage bimg = ImageIO.read(targetFile);
                int width = bimg.getWidth();
                int height = bimg.getHeight();
                BufferedImage thumbnail = ImageIO.read(newFile);
                int thumbnailWidth = thumbnail.getWidth();
                int thumbnailHeight = thumbnail.getHeight();
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("pictureHeight",height);
                map.put("pictureWidth",width);
                map.put("picturePath",picturePath+"/"+newName);
                map.put("thumbnailHeight",thumbnailHeight);
                map.put("thumbnailWidth",thumbnailWidth);
                map.put("thumbnailPath",picturePath+"/s"+newName);
                return map;
            } catch (IllegalStateException e) {
                e.printStackTrace();
                throw new BusinessException("图片上传失败");
            } catch (IOException e) {
                e.printStackTrace();
                throw new BusinessException("图片上传失败");
            } catch (Exception e) {
                e.printStackTrace();
                throw new BusinessException("图片上传失败");
            }
        }
        return null;
    }


Map前面三个字段显示的是原图宽高和路径,后三个字段显示的是压缩后的图的宽高路径

 

转自:https://blog.csdn.net/qq_39019735/article/details/82687244

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值