Determining the Format of an Image in a File

The javax.imageio package can determine the type of image in a file or input stream.
try { // 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) { } // Returns the format of the image in the file 'f'. // Returns null if the format is not known. public static String getFormatInFile(File f) { return getFormatName(f); } // Returns the format of the image in the input stream 'is'. // Returns null if the format is not known. public static String getFormatFromStream(InputStream is) { return getFormatName(is); } // Returns the format name of the image in the object 'o'. // 'o' can be either a File or InputStream object. // Returns null if the format is not known. private static String getFormatName(Object o) { try { // Create an image input stream on the image ImageInputStream iis = ImageIO.createImageInputStream(o); // Find all image readers that recognize the image format Iterator iter = ImageIO.getImageReaders(iis); if (!iter.hasNext()) { // No readers found return null; } // Use the first reader ImageReader reader = (ImageReader)iter.next(); // Close stream iis.close(); // Return the format name return reader.getFormatName(); } catch (IOException e) { } // The image could not be read return null; }

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.