Use thumbnails to achieve image compression of specified size

There is a requirement in the project to judge the image size of the upload server. Images greater than 500K should be compressed and uploaded after they are less than 500K.

Image compression can be realized through imageio of Java API, but after reading online blogs, it is generally said that there are many bugs and there will be oom memory overflow.

The thumbnails plug-in is a Google plug-in that can specify different parameters for compression. For example: width and height (size), scaling (scale), formulation of quality ratio (outputquality), etc.

The jar packages used by the plug-in are:

The code is as follows:

 /**
 *
 * @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,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,accuracy);
 }

Then compress the picture size:

commpressPicForScale(filePath,filePath,500,0.8);

Compression complete:

The above is the whole content of this article. I hope it will help you in your study, and I hope you will support us a lot.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>