Java ImageIO – Write image to file
This is an example of how to write an image to a file, making use of theImageIO utility class of Java.ImageIO class ofjavax.imageio package, provides methods to locateImageReaders andImageWriters, to perform encoding and decoding and other methods for image processing.
Among the methods ofImageIO class, there are thewrite(RenderedImage im, String formatName, File output),write(RenderedImage im, String formatName, ImageOutputStream output) andwrite(RenderedImage im, String formatName, OutputStream output) methods, that are used to write an image to a file. All methods make use of a aRenderedImage, which is the image to be written, and a StringformatName, which is the format of the image to be written. The first method supports the given format to aFile, the second one to anImageOutputStream and the third one to anOutputStream. All methods returnfalse if no appropriateImageWriter is found andtrue otherwise.
Below, we are using thewrite(RenderedImage im, String formatName, File output) method. The steps we are following are:
- Create a newFile instance, converting the given pathname string into an abstract pathname, which is the initial image in a
.jpgformat. - Read the already existing image. Use
read(File input)API method of ImageIO, with the file created above as parameter. It returns aBufferedImage as the result of decoding the file with anImageReader chosen automatically from among those currently registered. - Use the
write(RenderedImage im, String formatName, File output)to write the image to a file. The format may be different now.
Note that bothread andwrite methods may throw anIOException, so they are surrounded in atry-catch block.
Take a look at the code snippet below:
ImageIOExample.java
package com.javacodegeeks.snippets.enterprise;import javax.imageio.ImageIO;import java.io.File;import java.io.IOException;import java.awt.image.BufferedImage;public class ImageIOExample { public static void main( String[] args ){ imageIoWrite(); } public static void imageIoWrite() { BufferedImage bImage = null; try { File initialImage = new File("C://Users/Rou/Desktop/image.jpg"); bImage = ImageIO.read(initialImage); ImageIO.write(bImage, "gif", new File("C://Users/Rou/Desktop/image.gif")); ImageIO.write(bImage, "jpg", new File("C://Users/Rou/Desktop/image.png")); ImageIO.write(bImage, "bmp", new File("C://Users/Rou/Desktop/image.bmp")); } catch (IOException e) { System.out.println("Exception occured :" + e.getMessage()); } System.out.println("Images were written succesfully."); }}
This was an example of how to write an image to a file, using thejavax.imageio.ImageIO class.

Thank you!
We will contact you soon.




