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; }

Comments

3 Sep 2010 - 12:37am by tudor watches (not verified)

The camaraderie that Christian Dior wallet they have, and being able iwc watches to feel that they are Dior sunglasses welcome and they are wanted womens Nike jacket and they're not outcasts, said watches armani parent Michael Potter. Watching the Nike men clothing smile on his face says women's Nike jacket it all.

3 Sep 2010 - 12:48am by tudor watches (not verified)

In a porsche design watch competitive economy with a weak nike walking shoes job market, you can't afford nike girls shoes to have a less-than-perfect resume.

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.