How to write BufferedImage as PNG without compression?

I need to write BufferedImage as .png without compression. I looked around and came 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); } 

An exception is thrown here.

 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) 
+4
source share
1 answer

PNG images achieve compression by first applying filter prediction (you can choose one of five options), and then compress the prediction error using ZLIB. You cannot omit these two steps, what you can do is specify β€œNONE” as the prediction filter, and compressionLevel = 0 for ZLIB compression, which would roughly correspond to an uncompressed image. The javax.imageio.* Package does not allow (I think) to select these options, maybe you can try with this or this

+2
source

All Articles