thumbnailator图片循环压缩
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
public byte[] commpressPicCycle(MultipartFile multipartFile, long desFileSize,double accuracy){
try(ByteArrayOutputStream out = new ByteArrayOutputStream()){
long fileSize = multipartFile.getSize();
if(fileSize <= desFileSize * 1024){
return multipartFile.getBytes();
}
BufferedImage output = ImageIO.read(multipartFile.getInputStream());
int imgWidth = output.getWidth();
int imgHeight = output.getHeight();
int desWidth = new BigDecimal(imgWidth).multiply(
new BigDecimal(accuracy)).intValue();
int desHeight = new BigDecimal(imgHeight).multiply(
new BigDecimal(accuracy)).intValue();
output = Thumbnails.of(output).size(desWidth, desHeight).asBufferedImage();
String base64 = imageToBase64(output);
while (base64.length() - base64.length() / 8 * 2 > 204800) {
output = Thumbnails.of(output).scale(0.9f).asBufferedImage();
base64 = imageToBase64(output);
}
ImageIO.write(output, "jpg", out);
return out.toByteArray();
}catch (IOException e){
e.printStackTrace();
}
return null;
}
public static String imageToBase64(BufferedImage bufferedImage) {
BASE64Encoder encoder = new BASE64Encoder();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ImageIO.write(bufferedImage, "jpg", baos);
} catch (IOException e) {
e.printStackTrace();
}
return encoder.encode((baos.toByteArray()));
}