imageio
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 newImageInputStream
. - 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.