Thursday, December 16, 2010

How to convert images

javax.imageio.ImageIO let's you convert and save images from one format into another.It works using plug-in modules that handle various formats, including gif, png, bmp, jpg and others. We can use getWriterFormatNames() to find out all supported types.

String[] types = ImageIO.getWriterFormatNames();

  for (String name: types){
    System.out.println(name);
  }


Next, let's load our image into a BufferedImage which is a subclass of Image class:
File inputFile = new File("1.bmp");

  BufferedImage image = ImageIO.read(inputFile);

Finally convert the image:
File outputFile = new File("1.jpg");

  ImageIO.write(image, "jpg", outputFile);

In this example, the image file bmp was converted into a jpg image file.



Here's the complete source code. Enjoy.
private void convertBmpToJpg(File inputFile){
   BufferedImage image = null;

   try{
      //Read bmp image
      image = ImageIO.read(inputFile);

      File outputFile = new File("1.jpg");
      //Convert bmp to jpg
      ImageIO.write(image, "jpg", outputFile);

   }catch(Exception e){
    //Do something here
   }

}

Don't forget to include this:
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;

No comments:

Post a Comment