Search code examples
javaimagejai

Check if a file is an image


I am using JAI and create a file with:

PlanarImage img = JAI.create("fileload", myFilename);

I check before that line if the file exists. But how could I check if the file is a .bmp or a .tiff or an image file?

Does anyone know?


Solution

  • The Image Magick project has facilities to identify image and there's a Java wrapper for Image Magick called JMagick which I think you may want to consider instead of reinventing the wheel:

    http://www.jmagick.org

    I'm using Image Magick all the time, including its "identify" feature from the command line and it never failed once to identify a picture.

    Back in the days where I absolutely needed that feature and JMagick didn't exist yet I used to Runtime.exec() ImageMagick's identify command from Java and it worked perfectly.

    Nowadays that JMagick exist this is probably not necessary anymore (but I haven't tried JMagick yet).

    Note that it gives much more than just the format, for example:

    $  identify tmp3.jpg 
    tmp3.jpg JPEG 1680x1050 1680x1050+0+0 DirectClass 8-bit 293.582kb 
    
    $  identify tmp.png
    tmp.png PNG 1012x900 1012x900+0+0 DirectClass 8-bit 475.119kb