我正在尝试压缩png图像(6.8 MB)以减小其大小,但我面临的问题是我要放弃它的大部分内容。即使我评论这些行
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(0.9f);
我获取了截图中的图像,但大小为(812 KB)。随着线条我得到一个大小为(1.24 MB)的png图像,但在这两种情况下,我得到的图像如截图中没有不同的 quility(也有黑色背景)。如何更好地压缩图像?另外我认为我可以通过将浮点值设置在0-1之间来配置质量值,如下面的setCompressionQuality(0.9f);
package ImageCompressor;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
public class ImageComprossor {
public static void main(String[] args) {
BufferedImage img = null;
try {
File input = new File("strawberry.png");
BufferedImage image = ImageIO.read(input);
File compressedImageFile = new File("strawberry_compressed.png");
OutputStream os = new FileOutputStream(compressedImageFile);
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
ImageWriter writer = writers.next();
ImageOutputStream ios = ImageIO.createImageOutputStream(os);
writer.setOutput(ios);
ImageWriteParam param = writer.getDefaultWriteParam();
// Check if canWriteCompressed is true
if (param.canWriteCompressed()) {
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(0.9f);
}
// End of check
writer.write(null, new IIOImage(image, null, null), param);
} catch (IOException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
我必须在这个方法中设置png getImageWritersByFormatName(“png”);然后图像看起来相同,但尺寸更大 - &gt;它的大小是11.2MB。