How to write out PNG Images in Java

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

Previously, we have used ImageIO and JAI to handle images during conversion. Both Libraries currently are not able to fulfill our needs so we developed our own Encoder and Decoder Image Library called JDeli ( Java Decoding Encoding Library for Images). We also stated in our previous blog article why we are dropping ImageIO and JAI.

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

PngEncoder  pngEncoder =  new PngEncoder();
 
OutputStream   out     =  new FileOutputStream("myNewPngFile.png");
 
pngEncoder.write(bufferedImage, out);

We have also created a useful how to series on how to read and write various Image formats.

If you’re a first-time reader, or simply want to be notified when we post new articles and updates, you can keep up to date by social media (Twitter, Facebook and Google+) or the Blog RSS.

 

Related Posts:

The following two tabs change content below.

Ernest Duodu

Developer at IDRSolutions
Ernest is a developer at IDRSolutions. He focuses mainly on our JavaFX PDF Viewer implementation. He was a speaker at JavaOne 2014, where he did a joint session titled "Lessons learnt developing a NetBeans PDF viewer plugin in JavaFX". Aside programming, he also enjoys a wide variety of hobbies which includes sky-diving, photography, exercising and listening to music.
Ernest

About Ernest Duodu

Ernest is a developer at IDRSolutions. He focuses mainly on our JavaFX PDF Viewer implementation. He was a speaker at JavaOne 2014, where he did a joint session titled "Lessons learnt developing a NetBeans PDF viewer plugin in JavaFX". Aside programming, he also enjoys a wide variety of hobbies which includes sky-diving, photography, exercising and listening to music.

Leave a Reply

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

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>