how-to

Graphics

How to convert image to other format

For this sample you must use:

import java.awt.image;

When you have for example existed .jpg picture and you need convert it into .png, you can use this code:

try {      
  /* -- read image from .jpg format */
  BufferedImage image = ImageIO.read( new File( "c:\\test.jpg" ) );
      
  if ( image != null ) {        
    /* -- write image into new file in .png format */
    ImageIO.write( image, "png", new File( "c:\\test1.png" ) );  
  }
      
} catch (IOException ex) {
  Logger.getLogger(Window.class.getName()).log(Level.SEVERE, null, ex);
}

NOTE: Available formats for reading/writing you can get by this:

System.out.println( "For reading = " + Arrays.toString( ImageIO.getReaderFormatNames() ) );
System.out.println( "For writing = " + Arrays.toString( ImageIO.getWriterFormatNames() ) );

The output could be:

For reading = [BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG, JPEG, WBMP, GIF, gif]
For writing = [BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG, JPEG, WBMP, GIF, gif]