We will see how we can read an image using Java. We know there are several kinds of image formats such as JPEG, GIF, PNG, BMP, TIFF etc. Java has built-in Image I/O API in javax.imageio package and it can be used to load external image formats into its BufferedImage formats. By default, Image I/O supports image formats such as JPEG, PNG, GIF, BMP, WBMP. It can also be extensible to support additional image formats for TIFF and JPEG 2000.

Image I/O recognises the contents of the file as a JPEG format image, and decodes it into a BufferedImage which can be directly used by Java 2D.

Image can be load or read using following code snippets, where imagePath is the full path with image name from where the image can be read.

try {
      BufferedImage bufferedImage = ImageIO.read(new File(imagePath));
    } catch (Exception e) {
      e.printStackTrace();
    }

 

Image can be write using the following code snippets, where bufferedImage is the BifferedImage read using ImageIO.read(); format is the output image format; file is the new File() object created using image full output path with image name.

try {
        ImageIO.write(bufferedImage, format, file);
    } catch (Exception e) {
      e.printStackTrace();
    }

You can save the below image for reading and writing.

read/write image using java

Now I will put whole source code for reading from and writing to an image file using Java. You can customize as per your requirements.

package in.webtuts.test;

import in.webtuts.image.utils.FileUtils;

import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

import com.sun.image.codec.jpeg.ImageFormatException;

public class ImageReadWrite {

  /**
  *    Constants for image types or formats
  */
  private static final String IMAGE_EXT_JPG = "jpg";
  private static final String IMAGE_EXT_JPEG = "jpeg";
  private static final String IMAGE_EXT_PNG = "png";
  private static final String IMAGE_EXT_GIF = "gif";

  /**
  *    Exception message to be thrown when allowed image types are not read
  */
  public static final String IMAGE_ALLOW_TYPES = "Image types allowed - " + IMAGE_EXT_JPG + IMAGE_EXT_JPEG + IMAGE_EXT_PNG + IMAGE_EXT_GIF;

  /**
   * @param args
   */
  public static void main(String[] args) {
    /**
    *    Read the image, Desert.jpg, from Desktop/Pictures
    */
    BufferedImage bufferedImage = getImage("C:/Users/admin/Desktop/Pictures/Desert.jpg");
    /**
    *    Write to the image file, DesertOutput.jpg, to desktop
    */
    boolean isSuccess = writeImage(bufferedImage, "C:/Users/admin/Desktop", "DesertOutput.jpg", IMAGE_EXT_JPEG);
    /**
    *    Show success or failed message
    */
    if (isSuccess) {
      System.out.println("Image successfully written.");
    } else {
      System.out.println("Image writing failed.");
    }
  }

  /**
  *    Read image and return BufferedImage
  *    imageFullPath - full path of the image with image file name
  */
  public static BufferedImage getImage(String imageFullPath) {
    BufferedImage bufferedImage = null;
    try {
      if (imageFullPath == null) {
        throw new NullPointerException("Image full path cannot be null or empty");
      }
      /**
      *    Check if the selected file is an image
      */
      boolean isImage = isFileAnImage(imageFullPath);
      if (!isImage) {
        throw new ImageFormatException(IMAGE_ALLOW_TYPES);
      }
      String imagePath = imageFullPath;
      /**
      *    get BufferedImage and return it
      */
      bufferedImage = ImageIO.read(new File(imagePath));
    } catch (Exception e) {
      e.printStackTrace();
    }
    return bufferedImage;
  }

  /**
  *    Write to the image file
  *    bufferedImage - image
  *    outputPath - where image has to be written
  *    fileName - output file name with extension
  * format - output image file format
  */
  public static boolean writeImage(BufferedImage bufferedImage, String outputPath, String fileName, String format) {
    boolean isSuccess = true;
    if (bufferedImage == null || format == null) {
      throw new IllegalArgumentException();
    }
    try {
      String output = outputPath + File.separator + fileName;
      File file = new File(output);
      /**
      *    write BufferedImage to a file
      */
      ImageIO.write(bufferedImage, format, file);
    } catch (Exception e) {}
    return isSuccess;
  }

  /**
  *    Check a file is an image
  * imageName - image file name with extension
  */
  public static boolean isFileAnImage(String imageName) {
    if (imageName == null) {
      throw new NullPointerException("Image full path cannot be null or empty");
    }
    File imageFile = new File(imageName);
    String ext = getFileExtension(imageFile);
    if (IMAGE_EXT_GIF.equalsIgnoreCase(ext) || IMAGE_EXT_JPEG.equalsIgnoreCase(ext) || IMAGE_EXT_JPG.equalsIgnoreCase(ext)
        || IMAGE_EXT_PNG.equalsIgnoreCase(ext)) {
      return true;
    }
    return false;
  }

/**
     * Get file extension from the file
     *
     * @param file
     *            - file
     */
    public static String getFileExtension(File file) {
        if (file == null) {
            throw new NullPointerException("Image file cannot be null");
        }
        String name = file.getName();
        int lastDotIndex = name.lastIndexOf(".");
        if (lastDotIndex > 0 && lastDotIndex < (name.length() - 1)) {
            return name.substring(lastDotIndex + 1).toLowerCase();
        }
        return "";
    }
}

 

That’s all. Thank you for reading this article.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials | TwitterFacebook Google PlusLinkedin | Reddit

Leave a Reply

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