我编写了一个方法,应该使用 Java 中的 ImageIO 库来压缩 JPEG 图像。但是,当我尝试压缩一些图像时,它们的大小实际上会增加!(从大约 21 kb 到 36 kb)。知道为什么会这样吗?我的代码如下所示:
public boolean compressJPG(String originPath, String destinationPath){
float compression = 0.1f;
File in = new File(originPath);
File out = new File(destinationPath);
try {
RenderedImage image = ImageIO.read(in);
ImageWriter writer = null;
Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
if(iter.hasNext()){
writer = (ImageWriter) iter.next();
}
ImageOutputStream outStream = ImageIO.createImageOutputStream(out);
writer.setOutput(outStream);
MyImageWriteParam iwparam = new MyImageWriteParam();
iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT) ;
iwparam.setCompressionQuality(compression);
writer.write(null, new IIOImage(image, null, null), iwparam);
outStream.flush();
writer.dispose();
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
public float setJPGCompressionQuality(float quality) {
if (quality < 0.0F || quality > 1.0F) {
throw new IllegalArgumentException("Quality out-of-bounds!");
}
return 256 - (quality * 256);
}