Convert Images in Java

An example on converting images between JPG, PNG, GIF formats in Java in two simple steps.


Example



// Import for ImageIO class
import javax.imageio.*;

// Import for BufferedImage
import java.awt.image.*;

// Import for File, IOException is also raised but not used here.
import java.io.*;

class ConvertJPG
{

public static void main(String args[]) throws Exception
{
// Read the input image file using a static method read() in javax.imageio.ImageIO
BufferedImage bim=ImageIO.read(new File("C:/java/images/icon.png"));

// Convert the image that is read to PNG and it's name should be icon.png in the current directory
boolean written=ImageIO.write(bim,"PNG",new File("icon.png"));

// Convert the image that is read to GIF and it's name should be icon.gif in the current directory
boolean written1=ImageIO.write(bim,"GIF",new File("icon.gif"));

// Print whether converted to PNG
System.out.println("Is file written to PNG (T/F)? "+written);

// Print whether converted to GIF
System.out.println("Is file written to GIF (T/F)? "+written1);
}

}

Explanation


ImageIO is a class in the javax.imageio package.
read() is a static overloaded method in the ImageIO class.
Here, we've used read(File source_image_file) from which the image is read.
The read(File source_image_file) method returns java.awt.image.BufferedImage object representing the image that is read from the file.
java.awt.image.BufferedImage is a class implementing the java.awt.image.RenderedImage interface.

write() is also a overloaded static method of the javax.imageio.ImageIO class.
Here we've used write(RenderedImage img,String convert_format,File destination_image_file)

For the first parameter in write() method, we've sent bim which is an object of the java.awt.image.BufferedImage class representing the image that is read (here C:/java/images/icon.png).
This can be used because BufferedImage implements RenderedImage so a BufferedImage object is also a RenderedImage object.

boolean value is returned which says whether the conversion was successfully completed or not. true is returned when conversion is completed.



No comments: