java 压缩图片文件,并保证清晰度
时间: 2024-02-07 10:03:52 浏览: 31
您可以使用 Java 中的 ImageIO 和 BufferedImage 类来压缩图片文件并保证清晰度,以下是一个示例:
```java
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImageCompressor {
public static void main(String[] args) throws IOException {
File inputFile = new File("input.jpg"); // 原始图片文件
File outputFile = new File("output.jpg"); // 压缩后的图片文件
int maxWidth = 800; // 压缩后的最大宽度
int maxHeight = 600; // 压缩后的最大高度
float quality = 0.7f; // 压缩质量,取值范围 0.0f ~ 1.0f
// 读取原始图片
BufferedImage inputImage = ImageIO.read(inputFile);
// 计算压缩后的尺寸
int width = inputImage.getWidth();
int height = inputImage.getHeight();
if (width > maxWidth) {
height = (int) (height * maxWidth / (double) width);
width = maxWidth;
}
if (height > maxHeight) {
width = (int) (width * maxHeight / (double) height);
height = maxHeight;
}
// 创建压缩后的图片
BufferedImage outputImage = new BufferedImage(width, height, inputImage.getType());
// 压缩图片
Graphics2D graphics = outputImage.createGraphics();
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
graphics.drawImage(inputImage, 0, 0, width, height, null);
graphics.dispose();
// 写入压缩后的图片文件
ImageIO.write(outputImage, "jpg", outputFile);
// 打印压缩前后的图片尺寸和文件大小
System.out.println("压缩前:宽度=" + inputImage.getWidth() + ",高度=" + inputImage.getHeight() + ",文件大小=" + inputFile.length());
System.out.println("压缩后:宽度=" + outputImage.getWidth() + ",高度=" + outputImage.getHeight() + ",文件大小=" + outputFile.length());
}
}
```
在上面的示例中,我们首先读取原始图片,然后根据指定的最大宽度和最大高度计算出压缩后的尺寸,接着创建一个压缩后的 BufferedImage 对象,使用 Graphics2D 对象将原始图片绘制到压缩后的图片中,并使用 ImageIO 将压缩后的图片写入文件。在绘制图片时,我们使用了 RenderingHints 参数来提高压缩后图片的清晰度。最后,我们打印出了压缩前后的图片尺寸和文件大小,以供参考。