我正在尝试使用以下代码压缩java中的图像
ImageWriter writer = (ImageWriter) ImageIO.getImageWritersByMIMEType("image/jpeg").next();
JPEGImageWriteParam param = (JPEGImageWriteParam) writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionType("JPEG");
param.setCompressionQuality(0.2f);
param.setProgressiveMode( ImageWriteParam.MODE_DEFAULT );
writer.setOutput(ImageIO.createImageOutputStream(outputStream));
writer.write(null, new IIOImage(resizedImg, null, null), param);
第二行JPEGImageWriteParam param = (JPEGImageWriteParam) writer.getDefaultWriteParam();
抛出ClassCastException
如果我将其更改为ImageWriteParam param = writer.getDefaultWriteParam();
它会为行UnsupportedOperationException
抛出param.setProgressiveMode( ImageWriteParam.MODE_DEFAULT );
提前谢谢......
答案 0 :(得分:1)
ImageWriter#getDefaultWriteParam()
提供了ImageWriteParam
而非JPEGImageWriteParam
类型的对象,这就是为什么您会遇到类强制转换异常的原因。你应该做的是创建一个新的JPEGImageWriteParam
并使用它。
JPEGImageWriteParam param = new JPEGImageWriteParam(<pass your lacale here>);
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionType("JPEG");
param.setCompressionQuality(0.2f);
param.setProgressiveMode( ImageWriteParam.MODE_DEFAULT );
希望这有帮助。