Home » Desktop Java » imageio » Determine format of an image

About Ilias Tsagklis

Ilias Tsagklis
Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.

Determine format of an image

With this tutorial we are going to see how to determine the format of an image in a Java Desktop Application. You will find this particularly useful in applications that need to process large numbers of images. Additionally you can use these for input verification.

In short, to determine the format of an image all you have to do is:

  • Open a new File to the image you want to process.
  • Use ImageIO.createImageInputStream(file) to create a new ImageInputStream.
  • Use ImageIO.getImageReaders to get an iterator over the reader that can read that specific image.
  • Select the first ImageReader from the iterator.
  • And use ImageReader.getFormatName() to get the format of the Image.

Let’s see the code:

package com.javacodegeeks.snippets.desktop;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

public class DetermineFormatOfAnImage {

	public static void main(String[] args) throws IOException {

		// get image format in a file
	    File file = new File("newimage.jpg");

	    // create an image input stream from the specified file

  ImageInputStream iis = ImageIO.createImageInputStream(file);

  // get all currently registered readers that recognize the image format

  Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);

  if (!iter.hasNext()) {

throw new RuntimeException("No readers found!");

  }

  // get the first reader

  ImageReader reader = iter.next();

  System.out.println("Format: " + reader.getFormatName());

  // close stream

  iis.close();

	}

}

Output:

Format: JPEG

 
This was an example on how to determine format of an image.

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of