How to read PNG files in Java

In this article I will show you how to read PNG files in Java. I will show you how to do this using ImageIO, and secondly using JDeli.

We originally used ImageIO and JAI in our software but it didn’t meet our needs and so we created our own image library, JDeli.Our PNG encoder and decoder speeds up the process of reading and writing PNGs. JDeli also lets you set a compression limit, allowing you to choose the best compression or the fastest compression.

First a quick introduction to PNGs…

What is a PNG?

PNG stands for Portable Network Graphics. It is a lossless image format popular on the world wide web because it supports transparency in browsers.

How do I read PNG Files?

ImageIO

ImageIO is included in the JDK (Javadoc here). Here is how to read a png file with ImageIO:

File imageFile = new File("image.png");
BufferedImage image = ImageIO.read(imageFile);

JDeli

JDeli is IDRSolution’s Java Image library (Javadoc and download). There are two ways you can read PNG files with JDeli. As with ImageIO, you can use the image file as a parameter:

File imageFile = new File("image.png");
PngDecoder decoder = new PngDecoder();
BufferedImage image = decoder.read(imageFile);

Alternatively, you can use the raw image data:

PngDecoder decoder = new PngDecoder();
BufferedImage image = decoder.read(rawPngData);

You can find more tutorials in our series on handling common image formats in Java, JDeli and other image libraries, including how to write out PNG files in Java.

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 (TwitterFacebook and Google+) or the  Blog RSS.

Related Posts:

The following two tabs change content below.

Bethan Palmer

Developer at IDR Solutions
Bethan is a Java developer at IDR Solutions and was a speaker at JavaOne 2016. She has a degree in English Literature and in her spare time enjoys sports including running and handball.
Bethan

About Bethan Palmer

Bethan is a Java developer at IDR Solutions and was a speaker at JavaOne 2016. She has a degree in English Literature and in her spare time enjoys sports including running and handball.

3 thoughts on “How to read PNG files in Java

  1. Abel shaw

    it throws a exception using imageio.read() where the size of the file >50M

    • Abel shaw

      how to solve this exception?

    • Have you tried adding more memory with -Xmx command. Java converts into ARGB so 50meg file could be a large image.

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>