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!
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;
}
}
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();
}
}
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With