springMVC上传图片并压缩

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_39019735/article/details/82687244

今天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前面三个字段显示的是原图宽高和路径,后三个字段显示的是压缩后的图的宽高路径

放两张对比图上来看看

上面是压缩前原图有3.33M,下面是压缩后的图只有426kb

图好像有点怪怪的,不要在意这些!咱关注的是图片压缩!

溜了溜了!

猜你喜欢

转载自blog.csdn.net/qq_39019735/article/details/82687244