<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
// 将谋图片等比例压缩,压缩后最大长度不能超过 limit ,保证图片不变形
String imageUrl = "C:\\Users\\Administrator\\Pictures\\0.jpg";
BufferedImage bufferedImage = ImageIO.read(new FileInputStream(new File(imageUrl)));
int height = bufferedImage.getHeight();
int width = bufferedImage.getWidth();
double limit = 300.0;//临界值,保证图片的最大长度(或宽或高取最大)不超过此界限
double rate = getScale(height, width,limit);
System.out.println("应该缩放的比例值为 .. " + rate);
System.out.println(height);
System.out.println(width);
if (rate != 0) {
Thumbnails.of(imageUrl).scale(rate).toFile("C:\\Users\\Administrator\\Pictures\\333333.jpg");
}else {
//无需缩放
}
/**
* @param height 高
* @param width 宽
* @param limit 应当压缩到的最大值
* @return
*/
private static double getScale(int height, int width,double limit ) {
double rate = 0;//应该缩放的比例值
if (height <= limit && width <= limit) {
//未超过界限无需压缩
} else if (height > limit && width > limit) {//均超过界限
//取两者中最大长度来计算比例
rate = (height > width) ? limit/ height : limit/ width;
}else if (width > limit){//取宽计算
rate = limit / width;
} else if (height > limit) {//取高计算
rate = limit/ height;
}
return rate;
}
jdk 方式压缩
int doWithHeight = (int) (rate * height);
int dowithWidth = (int) (rate * width);
BufferedImage finalImage = new BufferedImage(dowithWidth, doWithHeight, BufferedImage.TYPE_INT_RGB);
finalImage.getGraphics().drawImage(bufferedImage.getScaledInstance(dowithWidth, doWithHeight, java.awt.Image.SCALE_SMOOTH), 0, 0, null);
//图片输出路径,以及图片名
FileOutputStream fileOutputStream = new FileOutputStream("C:\\Users\\Administrator\\Pictures\\44444.jpg");
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fileOutputStream);
encoder.encode(finalImage);
fileOutputStream.close();
/**
* 通过指定压缩质量压缩图片,并保存到目标文件
*/
public static void compressImageWithQuality(BufferedImage image, File outputFile, double compressionQuality) throws IOException {
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
ImageWriter writer = writers.next();
ImageOutputStream ios = ImageIO.createImageOutputStream(outputFile);
writer.setOutput(ios);
// 设置压缩质量参数
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality((float) compressionQuality);
// 写入文件
writer.write(null, new IIOImage(image, null, null), param);
// 关闭资源
ios.flush();
ios.close();
writer.dispose();
}