【Java】图片压缩处理

需求如下:

一些图片太大了,手机拍摄上传的图片有5M大小,然后阅读的内容其实不需要特别高的分辨率

1M以下的图片并不需要被压缩,压缩只是针对部分过大的图片处理

 

图片处理库:

我看了几篇,还是选代码量最少的用:

先要把文件写入服务器本地磁盘上,再用处理库读取进行处理输出

依赖坐标

<!-- https://mvnrepository.com/artifact/net.coobird/thumbnailator -->
<dependency>
    <groupId>net.coobird</groupId>
    <artifactId>thumbnailator</artifactId>
    <version>0.4.19</version>
</dependency>

 

参考博客:

https://blog.csdn.net/weixin_42031557/article/details/126100465

  

参考博客的写法会把原来的图片覆写掉,但是为了比较压缩差别,肯定不能覆写的

// 图片压缩
@Test
public void pictureCompressTest() {
    String src = "C:\\Users\\Administrator\\Desktop\\test.jpg";
    String dest = "C:\\Users\\Administrator\\Desktop\\test2.jpg";
    pictureCompress(src, dest, 1024 * 1024L, 0.5);
}

/**
 * 图片压缩处理方法
 * @param srcPath 图片源文件路径
 * @param destPath 输出文件路径
 * @param fileSize 限制在多大时停止压缩
 * @param accuracy 压缩图片的精细度
 */
@SneakyThrows
public static void pictureCompress(String srcPath, String destPath, long fileSize, double accuracy) {
    final File srcFile = new File(srcPath);
    long length = srcFile.length();
/* 如果图片本身不够大的话就不需要做任何处理 */ if (length < fileSize) return; BufferedImage bim = ImageIO.read(srcFile); 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(srcPath).size(desWidth, desHeight).outputQuality(accuracy).toFile(destPath);
   /* 压缩之后,使用输出后的文件递归,重复写入处理,直到大小满意 */ pictureCompress(destPath, destPath, fileSize, accuracy); }

 

 

posted @ 2023-03-12 19:24  emdzz  阅读(277)  评论(0编辑  收藏  举报