Java实现对图像文件的压缩
时间: 2023-10-13 18:06:50 浏览: 122
Java提供了多种压缩图像文件的方式,其中常用的包括JPEG和PNG压缩。
使用JPEG压缩:
```java
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class ImageCompressor {
public static void main(String[] args) throws IOException {
File originalFile = new File("original.jpg");
BufferedImage originalImage = ImageIO.read(originalFile);
File compressedFile = new File("compressed.jpg");
ImageIO.write(originalImage, "jpg", compressedFile);
}
}
```
使用PNG压缩:
```java
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
public class ImageCompressor {
public static void main(String[] args) throws IOException {
File originalFile = new File("original.png");
BufferedImage originalImage = ImageIO.read(originalFile);
File compressedFile = new File("compressed.png");
// Get the iterator for png writers
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("png");
if (!writers.hasNext()) {
throw new IllegalStateException("No writers found");
}
ImageWriter writer = writers.next();
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(0.5f); // Set the compression quality between 0 and 1
FileImageOutputStream output = new FileImageOutputStream(compressedFile);
writer.setOutput(output);
writer.write(null, new IIOImage(originalImage, null, null), param);
output.close();
}
}
```
其中,对于JPEG压缩,可以直接使用ImageIO.write()方法,指定输出文件格式为"jpg"即可;对于PNG压缩,需要使用ImageWriter并指定压缩参数,其中可以通过setCompressionQuality()方法设置压缩质量,值为0到1之间的float类型。
阅读全文