int originalWidth = originalImage.getWidth();
int originalHeight = originalImage.getHeight();
// 检查是否需要缩放
if (originalWidth <= maxWidth && originalHeight <= maxHeight) {
return; // 无需处理
}
// 计算缩放比例
double widthRatio = (double) maxWidth / originalWidth;
double heightRatio = (double) maxHeight / originalHeight;
double ratio = Math.min(widthRatio, heightRatio);
// 计算新尺寸
int newWidth = (int) (originalWidth * ratio);
int newHeight = (int) (originalHeight * ratio);
// 执行缩放
BufferedImage resizedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = resizedImage.createGraphics();
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics.drawImage(originalImage, 0, 0, newWidth, newHeight, null);
graphics.dispose();
// 获取文件扩展名
String formatName = originalPath.substring(originalPath.lastIndexOf(".") + 1);
try {
// 覆盖原文件
ImageIO.write(resizedImage, formatName, originalFile);
}catch (Exception e){
}
}`