How do I write a BufferedImage as a PNG with no co

2019-06-28 01:01发布

问题:

I need to write a BufferedImage as a .png with no compression performed. I've looked around, and come up with the following code.

public void save(String outFilePath) throws IOException {
    Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("png");
    ImageWriter writer = iter.next();

    File file = new File(outFilePath);      
    ImageOutputStream ios = ImageIO.createImageOutputStream(file);
    writer.setOutput(ios);

    ImageWriteParam iwp = writer.getDefaultWriteParam();
    iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    iwp.setCompressionQuality(1.0f);

    IIOImage image = new IIOImage(mapImage, null, null);

    writer.write(null, image, iwp);
    writer.dispose();

    //ImageIO.write(mapImage, "png", file);
}

Here's the exception being thrown.

Exception in thread "main" java.lang.UnsupportedOperationException: Compression not supported.
    at javax.imageio.ImageWriteParam.setCompressionMode(Unknown Source)
    at Map.MapTransformer.save(MapTransformer.java:246)
    at Map.MapTransformer.main(MapTransformer.java:263)

回答1:

PNG images achieve compression by first applying a prediction filter (you can choose among five variants), and then compressing the prediction error with ZLIB. You cannot omit these two steps, what you can do is to specify "NONE" as prediction filter, and compressionLevel=0 for the ZLIB compression, which would roughly correspond to a non-compressed image. The javax.imageio.* package does not allow (I think) to select this parameters, perhaps you can try with this or this