<dependency>
<groupId>org.imgscalr</groupId>
<artifactId>imgscalr-lib</artifactId>
<version>4.2</version> <!-- 请检查最新版本 -->
</dependency>
import org.imgscalr.Scalr;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImgscalrCompressor {
public static void compressImage(String inputImagePath, String outputImagePath, int maxWidth, int maxHeight) {
try {
// 读取原始图片
File inputFile = new File(inputImagePath);
BufferedImage image = ImageIO.read(inputFile);
// 使用 Imgscalr 进行图片压缩
BufferedImage resizedImage = Scalr.resize(image, Scalr.Method.QUALITY, maxWidth, maxHeight);
// 写入压缩后的图片
ImageIO.write(resizedImage, "jpg", new File(outputImagePath));
System.out.println("Image compressed successfully with Imgscalr!");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
compressImage("input.jpg", "output.jpg", 800, 600); // 压缩到最大800x600像素
}
}