Convert Image Formats

In this example we are converting image of any format
into jpg format.
Import java.io.* package and
class javax.imageio.ImageIO and java.awt.BufferedImage.
The package java.io.* is used for input and output
operations through data streams, serialization and the file system.
Classes ImageReader and ImagrWriter inherit the
static methods from the class javax.imageio..ImageIO for reading
and writing the images respectively. The class java.awt.BufferedImage
extends Image class
and implements WritableRenderedImage interface. The class BufferedImage
is used to access an image.
The methods used in this example are:
write(RenderedImage im, String formatName, File output): This method is used to
write an image. This method takes three parameters first one is
Renderedimage, second is format
in which the image is to be converted and last is name of the file on
which the image is to be writen. The format name may be gif, jpg, png etc.
read(File input) : This is used to read an image.
Code Description:
This example reads the image name passed at the command prompt for
converting the image into the jpg format. In this example we are reading the image from system by
using read() method of ImageIO class. We
are using write() method for conversion of an image of any
format into the jpg format.
Here is the code of the program :
import java.io.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
public class GIFToJPG
{
public static void main(String a[]){
try{
System.out.println("Enter image name\n");
BufferedReader bf=new BufferedReader(new
InputStreamReader(System.in));
String imageName=bf.readLine();
File input = new File(imageName);
BufferedImage image = ImageIO.read(input);
System.out.println("Enter the output image
name(.jpg):\n");
String imageName1=bf.readLine();
File output = new File(imageName1);
ImageIO.write(image, "jpg", output);
System.out.println("Your image has been
converted successfully");
}catch(FileNotFoundException e){
System.out.println("Error:"+e.getMessage());
}catch(IOException e)
{
System.out.println("Error:"+e.getMessage());
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
}
|
Input on DOS Prompts :
C:\image>javac GIFToJPG.java
C:\image>java GIFToJPG
Enter image name
rajeshxml2.gif
Enter the output image name(.jpg):
raju.jpg
Your image has been converted successfully
|
Input image:rajeshxml2.gif

Output of The Example:raju.jpg

Download this example.

|