<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.11</version>
</dependency>
package com.haoma.util.file;
import net.coobird.thumbnailator.Thumbnails;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
public class CommpressUtils {
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");
copyFile(srcPath,desPath);
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();
if (fileSize != 0 && fileSize <= desFileSize * 1024) {
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);
commpressPicCycle(desPath, desFileSize, accuracy);
}
public static void copyFile(String srcPath, String destPath) throws IOException {
FileInputStream fis = new FileInputStream(srcPath);
FileOutputStream fos = new FileOutputStream(destPath);
int len = 0;
byte[] b = new byte[1024];
while ((len = fis.read(b)) != -1) {
fos.write(b, 0, len);
}
fos.close();
fis.close();
}
}