我有一段压缩具有一定质量的jpg图像的代码,但是当图像是png类型时,它们都会变黑。知道为什么以及如何解决它?这是我的代码。
public void compressImage(String filename, ServletContext servletContext) {
//You first need to enumerate the image writers that are available to jpg
Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
//Then, choose the first image writer available
ImageWriter writer = (ImageWriter) iter.next();
//instantiate an ImageWriteParam object with default compression options
ImageWriteParam iwp = writer.getDefaultWriteParam();
//Set the compression quality
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(0.5f);
try {
BufferedImage img = ImageIO.read(new File(filename));
String destPath = "/Users/KingdomHeart/resources/scholar/compress/compress.jpg";
File file = new File(destPath);
FileImageOutputStream output = new FileImageOutputStream(file);
writer.setOutput(output);
IIOImage image = new IIOImage(img, null, null);
writer.write(null, image, iwp);
writer.dispose();
}catch(IOException e){
}
}
答案 0 :(得分:3)
这可能有你想要的答案:Converting transparent gif / png to jpeg using java
问题可能是您正在使用具有一定透明度的PNG。