0

I have a piece of code that compress an jpg image with a certain quality, but when the image is png type, they all turn black. Any idea why and how to fix it? here is my code.

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){

    }
}
Thang Pham
  • 38,125
  • 75
  • 201
  • 285

1 Answers1

3

This might have the answers you're looking for: Converting transparent gif / png to jpeg using java

The issue is likely that you're working with a PNG that has some transparency in it.

Community
  • 1
  • 1
no.good.at.coding
  • 20,221
  • 2
  • 60
  • 51