In this article, we will show you how to use ImageIO, JAI and JDeli to write out BufferedImages as PNG.
We previously used ImageIO to write PNG files, but over time became increasingly dissatisfied as we discovered more and more issues. Eventually we wrote our own PNG Encoder which fixes those issues and is now available as part of JDeli.
What is PNG
PNG stands for Portable Network Graphics.It is a raster graphic file format that supports lossless data compression. It is used widely on the world wide web as it supports transparency in browsers. Also PNG files are non lossy files and supports 8 and 24 bit colors.
The file name extension for PNG files is:
Example Java code to write PNG images in Java:
Here are some code examples using Image IO, JAI and JDeli to save a BufferedImage to a PNG format
– Using Image IO
Javadoc and included in JDK
File myNewPNGFile = new File("ImageAsPNG.png"); ImageIO.write(bufferedImage, "PNG", myNewPNGFile);
PNGEncodeParam param = PNGEncodeParam.getDefaultEncodeParam(bufferedImage); ImageEncoder encoder = ImageCodec.createImageEncoder("PNG", bufferedOutputStream, param); encoder.encode(bufferedImage);
– Using JDeli
You can easily replace ImageIO (and get much better support for PNG files) by just changing ImageIO.write to JDeli.write.
//Write Image (can also be OutputStream) File myNewPNGFile=new File("ImageAsPNG.png"); JDeli.write(myBufferedImage, "png", myNewPNGFile);
Or you can use the JDeli PngEncoder directly:
PngEncoder pngEncoder = new PngEncoder(); OutputStream out = new FileOutputStream("myNewPngFile.png"); pngEncoder.write(bufferedImage, out);
Why use JDeli?
JDeli offers a range of advantages over ImageIO and alternatives, including:
- prevents heap related JVM crashes
- implements unsupported image formats
- reduce output file size
- improve read/write performance
- supports threading
- superior image scaling algorithms
This article is part of our series on reading and writing image files in Java.
IDRsolutions develop a Java PDF library, a PDF forms to HTML5 converter, a PDF to HTML5 or SVG converter and a Java Image Library that doubles as an ImageIO replacement. On the blog our team post about anything interesting they learn about.