Handling images in java using imageIO

Have you ever faced the need of sending an image through a network using a Java program? If yes, you must have probably read the image to a byte array sent it through the network. The problem with this method is it is too long and you have to remake the image file ( using the received byte array) at the destination to take any use of it.

But in this article I’m going to show how to read an image to a Java class called “Image” and use it appropriately. You can use this “Image” class directly in GUI’s, send it through networks, store it, etc. Sol let’s look at the code now. The code consists of two parts. Reading the image to an instance of the “Image” class and writing it back to the hard drive. I have put comments in almost every step. So understanding the code should be easy.

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

public class Main {

 public void copyImage(){

 //path of the image to be read
 String path="picture.jpg";

 //create a file entry in java for that image
 File imageSrc=new File(path);

 if(!imageSrc.exists()){
 System.out.println("Input image does not exist.");
 System.exit(0);
 }

 try {

 /*
 * This part of the code is for reading the image in to
 * an instance of an Image class.
 */

 //Create a stream to read the image
 ImageInputStream iis = ImageIO.createImageInputStream(imageSrc);
 /*
 * ImageIO is a class containing static convenience methods for locating
 *ImageReaders and ImageWriters, and performing simple encoding and decoding.
 */

 //get a collection of Image readers which support jpg
 Iterator<?> imgReaders = ImageIO.getImageReadersByFormatName("jpg");

 //get the first image reader from the collection
 ImageReader reader = (ImageReader) imgReaders.next();

 //set the input for the image reader
 reader.setInput(iis, true);
 /*
 * Setting seekForwardOnly parameter ensures that the image file is
 * read in the ascending order.
 *
 */

 //to ensure that the default read parameters are used when
 //decoding data from the stream
 ImageReadParam param = reader.getDefaultReadParam();

 //read the image
 Image image = reader.read(0, param);

 /*
 *
 * This part of the code is for writing the image object
 * back to the hard disk as an image file.
 */

 //To render the image
 BufferedImage bufferedImage = new BufferedImage(image.getWidth(null),
image.getHeight(null), BufferedImage.TYPE_INT_RGB);

 //using "painter" we can draw in to "bufferedImage"
 Graphics2D painter = bufferedImage.createGraphics();

 //draw the "image" to the "bufferedImage"
 painter.drawImage(image, null, null);

 //the new image file
 File outputImg=new File("output.jpg");

 //write the image to the file
 ImageIO.write(bufferedImage, "jpg", outputImg);

 System.out.println("Image transfer was successful...!");

 } catch (IOException ex) {
 Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
 }
 }

 public static void main(String[] args) {
 // TODO code application logic here

 Main main=new Main();
 main.copyImage();
 }

}

You can download the text file from here.

As you must have understood, I have written the code to read a JPEG image. I tested the same code for BMP, PNG, and TIFF. All those formats worked just fine. The only draw back that I saw was there is a quality loss when using JPEG. To change the image format, change the following code segments (change xxx to the desired foramt).

//path of the image to be read

String path="picture.xxx";

————————————————————————————————————————————————————————–

//get a collection of Image readers which support jpg
 Iterator<?> imgReaders = ImageIO.getImageReadersByFormatName("xxx");

————————————————————————————————————————————————————————–

//the new image file
File outputImg=new File("output.xxx");

————————————————————————————————————————————————————————–

//write the image to the file
ImageIO.write(bufferedImage, "bmp", outputImg);

————————————————————————————————————————————————————————–

If you used a byte array to read the image file, you have to make an image file( on the hard drive) before you use that image again. But using the above method you can directly use it in the Java program. Click here to see an example on that.

As you can see, the possibilities are endless. So experiment and enjoy…..!

Share Button

6 thoughts on “Handling images in java using imageIO

  1. very helpful code very easy to use.
    Thanks a lot
    can we do same for videos??
    or if you know how to save video and audios please reply at given email
    thanks once again

  2. Your code example was a lot of help to me. I have to be able to read in a tiff image file, one that also includes “user defined” Ascii tag fields, then rotate the image (in the current case 180 degrees) and create a new tiff which contains the exact same tags (including orientation tag).

    Any hints or tips on that? Do you know if ImageIO has any way to preserve the current tags in the source image?

Leave a Reply to Daishy Cancel reply

Your email address will not be published. Required fields are marked *