Java Program-Convert PNG to JPG using JAI

In this example, we will use JAI (Java Advanced Imaging) API to convert a PNG image to JPEG format. This post is the last of the PNG to JPG compression series. I have provided some links below if you are keen on other parts of this series:

JPG Conversion using JAI

You need to download JAI from Oracle, and have the following JAR files in your class path for this example to work:
  • jai_codec.jar
  • jai_core.jar

Java Example – PNG to JPG

The complete Java example to convert PNG to JPG format using JAI (Java Advanced Imaging) framework is given below:
public class jai_png_jpg {
  public static void main(String[] args) throws Exception {
      String filename="input_png.png";
      //Read input PNG as a PlanarImage file
      PlanarImage inputfile = JAI.create("fileload", filename); 
      //write output in JPG Format 

Converted Image Size

We used three different approaches to convert PNG to JPG viz JAI, JMagick and ImageIO. A comparison of the output image file size in these cases is provided in the table below:

JMagick JAI ImageIO
171 Kb 112 Kb 112 Kb

This also creates more evidence that JPEG conversion uses identical algorithms in JAI and ImageIO libraries.

We will see how to deal with other complex image conversions in upcoming posts.

No comments:

Post a Comment