java 图片压缩策略兼容历史数据 Thumbnails

     上网找了好多关于图片压缩的帖子,基本上都是介绍谷歌Thumbnails和阿里simpleimage,自己写的也有,但我觉得还是大厂的成熟技术比较稳定,最后选择了Thumbnails。简介可参考https://www.xuebuyuan.com/3229489.html

    当前项目存在历史数据,而我又比较懒不想处理了,因而当前方案需要兼容历史数据,原来图片的命名方式是uuid+后缀,因此处理完的图片名称还是uuid+后缀,原图文件名称是uuid+"-initial"+后缀,图片超过200k处理。

 

 // 取UUID作为文件名
        String uuid = CommonUtil.getUUID().replaceAll("-", "");
//fileExt文件后缀
        String fileRelativePath= new StringBuffer(relativePath).append(uuid).append(fileExt).toString();
        String filePath = new StringBuffer(basePath).append(fileRelativePath).toString();
        String imgInitialRelativePath= new StringBuffer(relativePath).append(uuid)
        		.append("-initial").append(fileExt).toString();
        String imgPath = new StringBuffer(basePath).append(imgInitialRelativePath).toString();
        
        //保存原文件 
        File file = new File(filePath);
        fileItem.write(file); 
        
        Pattern reg = Pattern.compile("[\\.](jpg|png|jpeg|gif|JPG|PNG|JPEG|GIF)$");
        Matcher matcher = reg.matcher(fileExt);
		if (matcher.find()) {	
	        //图片压缩 超200k压缩
	        if(fileItem.getSize()>204800){
	         //若图片较大需要将原文件重命名为XX-initial
	          File imgBig = new File(imgPath);
	          file.renameTo(imgBig);
	          imgPress(imgBig,imgPath,new StringBuffer(basePath).append(relativePath).append(uuid)
	                .append(fileExt).toString());
	        }
	      
		}

  图片压缩策略:考虑本次目标是手机上传图片,一般都是尺寸像素比较大,因此采用缩小像素的方式,图片保持等比例,横竖版照片不超过480*270(这里想要压的更小可以将目标尺寸调的更小),不做放大处理。

private void imgPress(File file,String sourcePath,String targetPath) throws Exception{
		FileInputStream inStream = new FileInputStream(file);
		BufferedImage sourceImg =ImageIO.read(inStream);
		int imgWidth=sourceImg.getWidth();
		int imgHeight=sourceImg.getHeight();
		double scaleW,scaleH;
		if(imgWidth>imgHeight){
			//横版图片
			scaleW=((double)imgWidth)/((double)480);
			scaleH=((double)imgHeight)/((double)270);
		}else{
			//竖版图片
			scaleW=((double)imgWidth)/((double)270);
			scaleH=((double)imgHeight)/((double)480);
		}
		double rate = scaleW > scaleH ? scaleW : scaleH;
		int scaleActualW,scaleActualH;
		 // 最小比率为1
        if (rate <= 1){
        	rate = 1;
        }
		scaleActualW = (int) (((double)imgWidth)/rate);
		scaleActualH = (int) (((double)imgHeight)/rate);
		Thumbnails.of(sourcePath).size(scaleActualW,scaleActualH).keepAspectRatio(false).toFile(targetPath);	
    }

  图片压完还是小了不少,也没压特别厉害,后续优化待补充吧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值