java压缩图片质量
时间: 2023-11-10 14:00:57 浏览: 134
可以使用Java的javax.imageio包中的ImageWriter来压缩图片质量。下面是一个简单的示例代码:
```java
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
public class ImageCompressionExample {
public static void compressImageQuality(File inputFile, File outputFile, float quality) throws IOException {
BufferedImage image = ImageIO.read(inputFile);
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpeg");
if (!writers.hasNext()) {
throw new IllegalStateException("No writers found");
}
ImageWriter writer = writers.next();
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(quality);
writer.setOutput(ImageIO.createImageOutputStream(outputFile));
writer.write(null, new IIOImage(image, null, null), param);
writer.dispose();
}
public static void main(String[] args) {
try {
File inputFile = new File("input.jpg");
File outputFile = new File("output.jpg");
// 压缩图片质量为0.5(50%)
compressImageQuality(inputFile, outputFile, 0.5f);
System.out.println("Image compression complete");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
上述代码将读取名为"input.jpg"的原始图片文件,并将压缩后的图像保存为"output.jpg",压缩质量为0.5(50%)。你可以根据需要调整压缩质量的值来获得不同质量的图像。
阅读全文