Java provides the ImageIO to work with image files. This example demonstrates how to get the type or format of the image file. It is necessary to know the type of the file when you are processing the images. Java has ImageReader which stores the type of image file. One image can have more that one readers associated with that file.
If you look at the below example, I have read a JPEG file and then printing the image format using the ImageIO classes.
ImageFormatExample.java
package javabeat.net.core; 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; /** * Get Image Format Example * * @author Krishna * */ public class ImageFormatExample { public static void main(String[] args) throws IOException { //Create Image File File imageFile = new File("Desert.jpg"); //Create ImageInputStream using Image File ImageInputStream imageInputStream = ImageIO.createImageInputStream(imageFile); //Get the image readers for that file Iterator<ImageReader> imageReadersList = ImageIO.getImageReaders(imageInputStream); if (!imageReadersList.hasNext()) { throw new RuntimeException("Image Readers Not Found!!!"); } //Get the image type ImageReader reader = imageReadersList.next(); System.out.println("Image Format: " + reader.getFormatName()); //Close stream (best practice) imageInputStream.close(); } }
Output…
Image Format: JPEG