Determining the Format of an Image in a File - Java 2D Graphics

Java examples for 2D Graphics:Image File

Description

Determining the Format of an Image in a File

Demo Code


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

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

public class Main {
  public static void m() {
    try {//from ww w.  j  ava 2 s. com
      // Get image format in a file
      File file = new File("image.gif");
      String formatName = getFormatName(file);
      // e.g. gif

      // Get image format from an input stream
      InputStream is = new FileInputStream(file);
      formatName = getFormatName(is);
      is.close();
    } catch (IOException e) {
    }
  }
  public static String getFormatInFile(File f) {
    return getFormatName(f);
  }
  public static String getFormatFromStream(InputStream is) {
    return getFormatName(is);
  }
  private static String getFormatName(Object o) {
    try {
      ImageInputStream iis = ImageIO.createImageInputStream(o);
      Iterator iter = ImageIO.getImageReaders(iis);
      if (!iter.hasNext()) {
        // No readers found
        return null;
      }

      // Use the first reader
      ImageReader reader = (ImageReader) iter.next();

      iis.close();
      return reader.getFormatName();
    } catch (IOException e) {
    }
    // The image could not be read
    return null;
  }
}

Related Tutorials