Java使用thumbnailator进行图片压缩处理

-- 添加依赖

<!-- 图片缩略图 -->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>

-- 测试代码类

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;

import javax.imageio.ImageIO;

import net.coobird.thumbnailator.Thumbnails;

public class ImageTest {

public static void main(String[] args) {
try {
commpressPicCycle("C:\\Users\\Justin\\Desktop\\下载\\temp\\IMG_0004.JPG",1024,0.8);
} catch (IOException e) {
e.printStackTrace();
}
}
// 压缩图片
private static void commpressPicCycle(String desPath, long desFileSize, double accuracy) throws IOException {
System.out.println("压缩开始。。。");
File srcFileJPG = new File(desPath);
long srcFileSizeJPG = srcFileJPG.length();
System.out.println(srcFileSizeJPG);
// 2、判断大小,如果小于1M,不压缩;如果大于等于1M,压缩
if (srcFileSizeJPG <= desFileSize * 1024) {
return;
}
// 计算宽高
BufferedImage bim = ImageIO.read(srcFileJPG);
int srcWdith = bim.getWidth();
int srcHeigth = bim.getHeight();
int desWidth = new BigDecimal(srcWdith).multiply(new BigDecimal(accuracy)).intValue();
int desHeight = new BigDecimal(srcHeigth).multiply(new BigDecimal(accuracy)).intValue();

Thumbnails.of(desPath).size(desWidth, desHeight).outputQuality(accuracy).toFile(desPath);
System.out.println("压缩结束。。。");
commpressPicCycle(desPath, desFileSize, accuracy);
}
}

 

posted @ 2022-05-31 17:32  孤舟蓑笠翁·  阅读(339)  评论(0编辑  收藏  举报