Detect the file type of the input stream prior to reading the image : ImageReader « 2D Graphics GUI « Java

Detect the file type of the input stream prior to reading the image


import java.awt.image.BufferedImage;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;

public class Main {
  public static void main(String[] argv) throws Exception {
    ImageInputStream imageStream = ImageIO.createImageInputStream(new URL("").openStream());
    Iterator<ImageReader> readers = ImageIO.getImageReaders(imageStream);
    ImageReader reader = null;
    if (!readers.hasNext()) {
    } else {
      reader =;
    String formatName = reader.getFormatName();
    if (!formatName.equalsIgnoreCase("jpeg") && !formatName.equalsIgnoreCase("png")
        && !formatName.equalsIgnoreCase("gif")) {
    reader.setInput(imageStream, true, true);
    BufferedImage theImage =;


Related examples in the same category

1.Show Image with ImageReader
2.Add Image IO Read Progress Listener to ImageReader
3.Read an Image from a file
4.Read an Image from inputStream
5.Read an Image from URL
6.Determining the Format of an Image in a File
7.List the image formats that can be read and written
8.Get file format, image resolution, number of bits per pixel (JPEG, GIF, BMP, PCX, PNG, IFF, RAS, PBM, PGM, PPM, PSD and SWF files)
9.Image format info
10.Image observer blocks until the image is completely loaded. AWT defers the loading of images until they are painted on a graphic.