Convert PNG to JPG Using ImageIO Java Example

ImageIO [javax.imageio.ImageIO] is a powerful Java class that can greatly simplify your needs to convert images from one format to another. This is supplied along with a standard Java installation and is used for common image manipulations.

We will explain how to use ImageIO class to convert a PNG image to JPEG format in this example.

Input PNG Image – Example

You can use any PNG image for this program to work. The one we are going to use is a 124 Kb image file. In one of our previous articles, we explained how to use JMagick to convert PNG to JPG. We are using the same image file here to see which library performs better under standard conditions.

ImageIO- PNG to JPG – Java Program

Here we present the complete Java code that creates a JPG version of the PNG image using ImageIO. It is provided below:

//we read PNG image using this class
import java.awt.image.BufferedImage;
//Used for conversion
import javax.imageio.ImageIO;
//Used to read input image through file
public class imageio_png_jpg {
  public static void main(String[] args) throws Exception {
      BufferedImage input_image = null; 
      //read PNG image as BufferedImage
      input_image = File("input_png.png"));
      //JPG output
      File outputfile = new File("jpg_converted.jpg"); 
      //write output in JPG format
      ImageIO.write(input_image, "jpg", outputfile);    

Convert PNG to JPG – Results

ImageIO converted PNG to JPG image had a size of 112 Kb. Far less that a JMagick converted one.

In the next post, we will discuss how to use Java advanced imaging library to do the same conversion, through an example.

No comments:

Post a Comment