nfsu
nfsu

Reputation: 113

Can you check whether a file is really an image in Java?

I'm learning to program in Java and right now I'm trying to make a program with GUI in Swing, which would make a slideshow out of images in a given directory. Now, my question is can you check whether a file is really an image?

I'm talking about a file that not only has the correct extension, like e.g. .jpg or .png, but also contains content that is.. interpretable as an image I guess? My wording here might not be precise.

I know I'm asking for quite a bit, but I'd be very grateful if someone could answer that. (Not a duplicate of Test if a file is an image file, because I think that the author there meant the extensions themselves).

Upvotes: 3

Views: 5734

Answers (2)

Andreas
Andreas

Reputation: 159086

Most image files start with a magic number, so for a quick check, look for that.

E.g. a PNG file always start with bytes 89 50 4E 47 0D 0A 1A 0A.

I'll leave the research for magic numbers of whatever image formats you want to support up to you.

UPDATE: See also list of file signatures on Wikipedia (courtesy of DevilsHnd).

Upvotes: 5

Daniel Centore
Daniel Centore

Reputation: 3349

I would just try loading it as an image and seeing if you get an image:

import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class Main
{
    public static void main(String[] args) throws IOException
    {
        System.out.println(isImage(new File("./dataset1.csv")));  // false
        System.out.println(isImage(new File("./graph.png")));  // true
    }

    public static boolean isImage(File file)
    {
        try {
            return ImageIO.read(file) != null;
        } catch (Exception e) {
            return false;
        }
    }
}

Upvotes: 5

Related Questions