The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > javax.imageio  [6 examples]

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

 Related Examples
e694. Reading an Image from a File, InputStream, or URL
e695. Saving a Generated Graphic to a PNG or JPEG File
e696. Listing the Image Formats That Can Be Read and Written
e697. Determining If an Image Format Can Be Read or Written
e699. Compressing a JPEG File


© 2002 Addison-Wesley.