Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if file is a valid jpg

Tags:

java

I would like to check if the file I am reading in from a directory is a jpg but I do not want to simply check the extension. I am thinking an alternative is to read the header. I have done some research and I want to use

ImageIO.read

I have seen the example

String directory="/directory";     

BufferedImage img = null;
try {
   img = ImageIO.read(new File(directory));
} catch (IOException e) {
   //it is not a jpg file
}

I am not sure where to go from here, it takes in the entire directory... but I need each jpg file in the directory. Can someone tell me what is wrong with my code or what additions need to be made?

Thank you!

like image 685
Teddy13 Avatar asked Mar 21 '13 04:03

Teddy13


3 Answers

Improving the answer given by @karthick you can do the following:

private static Boolean isJPEG(File filename) throws IOException {
    try (DataInputStream ins = new DataInputStream(new BufferedInputStream(new FileInputStream(filename)))) {
        return ins.readInt() == 0xffd8ffe0;
    }
}
like image 101
LamerGamerYT Avatar answered Oct 06 '22 05:10

LamerGamerYT


You can read the first bytes stored in the buffered image. This will give you the exact file type

Example for GIF it will be
GIF87a or GIF89a 

For JPEG 
image files begin with FF D8 and end with FF D9

http://en.wikipedia.org/wiki/Magic_number_(programming)

Try this

  Boolean status = isJPEG(new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\Chrysanthemum.jpg"));
System.out.println("Status: " + status);


private static Boolean isJPEG(File filename) throws Exception {
    DataInputStream ins = new DataInputStream(new BufferedInputStream(new FileInputStream(filename)));
    try {
        if (ins.readInt() == 0xffd8ffe0) {
            return true;
        } else {
            return false;

        }
    } finally {
        ins.close();
    }
}
like image 10
karthick Avatar answered Oct 31 '22 20:10

karthick


You will need to get the readers used to read the format and check that there are no readers available for the given file...

String fileName = "Your image file to be read";
ImageInputStream iis = ImageIO.createImageInputStream(new File(fileName ));
Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("jpg");
boolean canRead = false;
while (readers.hasNext()) {
    try {        
        ImageReader reader = readers.next();
        reader.setInput(iis);
        reader.read(0);
        canRead = true;
        break;
    } catch (IOException exp) {
    }        
}

Now basically, if none of the readers can read the file, then it's not a Jpeg

Caveat

This will only work if there are readers available for the given file format. It might still be a Jpeg, but no readers are available for the given format...

like image 4
MadProgrammer Avatar answered Oct 31 '22 20:10

MadProgrammer