Question

I have requirement to get from user input file which should be image only of specified type. E.g. only JPEGs. Other files must be rejected.

So I implemented naive basic check for file

fileName.toLowerCase().endsWith(".jpg") || fileName.toLowerCase().endsWith(".jpeg")

So if user uploaded file.png, this file was rejected. But then users realized, that if they simply rename file.png to file.jpg, the file will be uploaded.

Is there way to detect if supplied file is valid image of given type using only JAVA SDK without external jars? (note I'm still working with JDK6). Thanks.

Was it helpful?

Solution

It should be relatively easy to do some naive checking to separate a JPEG from a PNG. According to Wikipedia, JPEG files always start with FF D8. PNGs however seem to start with 89 50, so one can easily distinguish between the two from just reading a byte or two from the file.

I would recommend looking up the file formats of the most important image types just to make sure there isn't some other mainstream one starting with FF D8. It seems unlikely however.

Edit: JPEG, PNG, GIF, BMP and TIFF all seem to have magic values at the start of the files to tell them apart form other types.

OTHER TIPS

Decode the file as jpeg and see if it throws an Exception or returns an image?

You can use JDK ImageIO to do this (http://docs.oracle.com/javase/6/docs/api/javax/imageio/ImageIO.html). Start by obtaining ImageReader for jpeg, then let that reader attempt to read the image.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top