0

我有一段代码可以压缩具有一定质量的 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){

    }
}
4

1 回答 1

3

这可能有您正在寻找的答案:Converting transparent gif / png to jpeg using java

问题可能在于您正在使用具有一定透明度的 PNG。

于 2011-03-14T21:13:33.030 回答