下面是使用thumbnailator依赖编写的一个压缩图片类的详细代码示例,该类会对大小超过1MB的图片进行无限循环压缩。
java Copy code
 import java.awt.image.BufferedImage;
 import java.io.File;
 import java.io.IOException;
 import javax.imageio.ImageIO;
 import net.coobird.thumbnailator.Thumbnails;
public class ImageCompressor {
     private static final long MAX_SIZE = 1_000_000; // 1MB
    public static void main(String[] args) throws IOException {
         String imagePath = "path/to/your/image.jpg";
         compressImage(imagePath);
     }
    public static void compressImage(String imagePath) throws IOException {
         File imageFile = new File(imagePath);
        while (imageFile.length() > MAX_SIZE) {
             BufferedImage image = ImageIO.read(imageFile);
             int width = image.getWidth();
             int height = image.getHeight();
            Thumbnails.of(imageFile)
                     .size(width / 2, height / 2) // 缩小图片为原始大小的一半
                     .outputQuality(0.9) // 压缩质量为90%
                     .toFile(imageFile);
         }
        System.out.println("Image compressed successfully!");
     }
 }
 在上述示例中,我们首先指定了要处理的图像文件路径imagePath,然后调用compressImage()方法来实现无限循环压缩。其中,我们使用ImageIO.read()方法读取图像文件并获取其宽度和高度。然后,我们使用Thumbnails.of()方法以及链式调用.size(width / 2, height / 2)将图像大小缩小为原始大小的一半,并使用.outputQuality(0.9)设置压缩质量为90%。最后,我们将结果保存回原始图像文件。
在每次循环迭代中,我们检查图像文件大小是否仍然超过1MB(MAX_SIZE)。如果是,则继续进行下一次循环迭代,直到图像大小小于等于1MB为止。
请确保将thumbnailator库添加到项目的依赖中,并根据实际情况替换示例代码中的图像路径。