I have requirement to get from user input file which should be image only of specified type. E.g. only JPEG
s. 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.
probeContentType() method. On Windows, this uses the file extension and the registry (it does not probe the file content). You can then check the second part of the MIME type and check whether it is in the form <X>/image .
If you are having trouble and want to check if you photo is a JPEG, look at the writing under the photo in its file name. If it ends . jpg or . jpeg- then the file is a JPEG and will upload.
By default, Java supports only these five formats for images: JPEG, PNG, BMP, WEBMP, GIF. If we attempt to work with an image file in a different format, our application will not be able to read it and will throw a NullPointerException when accessing the BufferedImage variable.
Just check if it starts with image/ . String fileName = uploadedFile. getFileName(); String mimeType = getServletContext(). getMimeType(fileName); if (mimeType.
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.
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.
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