Determining If an Image Format Can Be Read or Written

By default, the javax.imageio package can read GIF, PNG, and JPEG images and can write PNG and JPEG images. This example demonstrates how to determine if a particular image format can be either read or written using the javax.imageio package.
boolean b; // Check availability using a format name b = canReadFormat("foo"); // false b = canReadFormat("gif"); // true b = canReadFormat("giF"); // true b = canWriteFormat("foo"); // false b = canWriteFormat("gif"); // false b = canWriteFormat("PNG"); // true b = canWriteFormat("jPeG"); // true // Get extension from a File object File f = new File("image.jpg"); String s = f.getName().substring(f.getName().lastIndexOf('.')+1); // Check availability using a filename extension b = canReadExtension(s); b = canWriteExtension(s); // Check availability using a MIME type b = canReadMimeType("image/jpg"); // false b = canReadMimeType("image/jpeg"); // true b = canWriteMimeType("image/gif"); // false b = canWriteMimeType("image/jPeg"); // true // Returns true if the specified format name can be read public static boolean canReadFormat(String formatName) { Iterator iter = ImageIO.getImageReadersByFormatName(formatName); return iter.hasNext(); } // Returns true if the specified format name can be written public static boolean canWriteFormat(String formatName) { Iterator iter = ImageIO.getImageWritersByFormatName(formatName); return iter.hasNext(); } // Returns true if the specified file extension can be read public static boolean canReadExtension(String fileExt) { Iterator iter = ImageIO.getImageReadersBySuffix(fileExt); return iter.hasNext(); } // Returns true if the specified file extension can be written public static boolean canWriteExtension(String fileExt) { Iterator iter = ImageIO.getImageWritersBySuffix(fileExt); return iter.hasNext(); } // Returns true if the specified mime type can be read public static boolean canReadMimeType(String mimeType) { Iterator iter = ImageIO.getImageReadersByMIMEType(mimeType); return iter.hasNext(); } // Returns true if the specified mime type can be written public static boolean canWriteMimeType(String mimeType) { Iterator iter = ImageIO.getImageWritersByMIMEType(mimeType); return iter.hasNext(); }

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.