我编写了一个方法,应该使用Java中的ImageIO lib压缩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);
}
答案 0 :(得分:2)
可能由于模式ImageWriteParam.MODE_EXPLICIT而发生。
如果交点非空,则将从第一个二次采样像素开始写入,并根据IIOParam.setSourceSubsampling指定的水平和垂直子采样因子在相交边界内包含其他像素。
使用MODE_DEFAULT而不是MODE_EXPLICIT。