Java ImageIO – Write image to file
This is an example of how to write an image to a file, making use of the ImageIO utility class of Java. ImageIO class of javax.imageio package, provides methods to locate ImageReaders and ImageWriters, to perform encoding and decoding and other methods for image processing.
Among the methods of ImageIO class, there are the write(RenderedImage im, String formatName, File output)
, write(RenderedImage im, String formatName, ImageOutputStream output)
and write(RenderedImage im, String formatName, OutputStream output)
methods, that are used to write an image to a file. All methods make use of a a RenderedImage, which is the image to be written, and a String formatName
, which is the format of the image to be written. The first method supports the given format to a File, the second one to an ImageOutputStream and the third one to an OutputStream. All methods return false
if no appropriate ImageWriter is found and true
otherwise.
Below, we are using the write(RenderedImage im, String formatName, File output)
method. The steps we are following are:
- Create a new File instance, converting the given pathname string into an abstract pathname, which is the initial image in a
.jpg
format. - Read the already existing image. Use
read(File input)
API method of ImageIO, with the file created above as parameter. It returns a BufferedImage as the result of decoding the file with an ImageReader 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 both read
and write
methods may throw an IOException, so they are surrounded in a try-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 the javax.imageio.ImageIO class.
Thanks. I was looking for the example.