当前位置: 移动技术网 > IT编程>移动开发>Android > 使用Thumbnails实现图片指定大小压缩

使用Thumbnails实现图片指定大小压缩

2019年09月09日  | 移动技术网IT编程  | 我要评论

诸城家教,求魔笔趣阁,酵父酵素

项目中有个要求,对上传服务器的图片大小进行判断,大于500k的图片要进行压缩处理,让其小于500k后在上传。

可以通过java api的imageio实现图片压缩,但是看了网上的博客普遍都说bug比较多,会有oom内存溢出的现象。

thumbnails插件是google的插件,能指定不同的参数进行压缩操作。
比如:宽高(size),缩放(scale),制定质量比(outputquality)等。

插件使用的jar包为:

thumbnailator-0.4.8.jar

代码如下:

 /**
 * 
 * @param srcpath 原图片地址
 * @param despath 目标图片地址
 * @param desfilesize 指定图片大小,单位kb
 * @param accuracy 精度,递归压缩的比率,建议小于0.9
 * @return
 */
 public static string commpresspicforscale(string srcpath,string despath,
 long desfilesize , double accuracy){
 try {
 file srcfile = new file(srcpath);
 long srcfilesize = srcfile.length();
 system.out.println("原图片:"+srcpath + ",大小:" + srcfilesize/1024 + "kb");
 //递归压缩,直到目标文件大小小于desfilesize
 commpresspiccycle(despath, desfilesize, accuracy);
 
 file desfile = new file(despath);
 system.out.println("目标图片:" + despath + ",大小" + desfile.length()/1024 + "kb");
 system.out.println("图片压缩完成!");
 } catch (exception e) {
 e.printstacktrace();
 }
 return despath;
 }

 public static void commpresspiccycle(string despath , long desfilesize,
 double accuracy) throws ioexception{
 file imgfile = new file(despath);
 long filesize = imgfile.length();
 //判断大小,如果小于500k,不压缩,如果大于等于500k,压缩
 if(filesize <= desfilesize * 500){
 return;
 }
 //计算宽高
 bufferedimage bim = imageio.read(imgfile);
 int imgwidth = bim.getwidth();
 int imgheight = bim.getheight();
 int deswidth = new bigdecimal(imgwidth).multiply(
    new bigdecimal(accuracy)).intvalue();
  int desheight = new bigdecimal(imgheight).multiply(
    new bigdecimal(accuracy)).intvalue();
  thumbnails.of(despath).size(deswidth, desheight).outputquality(accuracy).tofile(despath);
  //如果不满足要求,递归直至满足小于1m的要求
  commpresspiccycle(despath, desfilesize, accuracy);
 }

然后压缩图片大小:

commpresspicforscale(filepath, filepath, 500, 0.8);

压缩完成:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网