Ernest Duodu Ernest is a Java developer. Outside programming, he also enjoys a wide variety of hobbies which includes sky-diving, photography, exercising and listening to music.

How to write out PNG Images in Java

1 min read

In this article, we will show you how to use ImageIO, JAI and JDeli to write out Buffered Images as PNG.

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: .png

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

– Using JAI
Javadoc and Download

PNGEncodeParam param = PNGEncodeParam.getDefaultEncodeParam(bufferedImage);
 
ImageEncoder encoder = ImageCodec.createImageEncoder("PNG", bufferedOutputStream, param); 
 
encoder.encode(bufferedImage);

– Using JDeli

Javadoc and Download

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

JDeli provides a complete PNG converter as it can read and write PNG image files and many other image formats.

JDeli can also read and write a very wide range of image formats. Here is the full list on Image file conversions supported.

I hope you found this useful. You can find more tutorials in our series on handling common image formats in Java, JDeli and other image libraries.

 

IDRsolutions develop a Java PDF Viewer and SDK, an Adobe forms to HTML5 forms converter, a PDF to HTML5 converter and a Java ImageIO replacement. On the blog our team post anything interesting they learn about.

Ernest Duodu Ernest is a Java developer. Outside programming, he also enjoys a wide variety of hobbies which includes sky-diving, photography, exercising and listening to music.

How to choose JPG versus JPEG2000 for image files

Since we started to support both JPG and JPG2000 as image file outputs in our software, we have found that this is a very...
Mark Stephens
1 min read

Leave a Reply

Your email address will not be published. Required fields are marked *

IDRsolutions Ltd 2019. All rights reserved.