Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if given file is image and is valid image of specific type in java

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.

like image 592
user3195535 Avatar asked Jan 15 '14 09:01

user3195535


People also ask

How do you check if a file is image or not in Java?

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 .

How can I tell what file type an image is?

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.

What is type of image in Java?

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.

How do I know if my image is uploaded or not?

Just check if it starts with image/ . String fileName = uploadedFile. getFileName(); String mimeType = getServletContext(). getMimeType(fileName); if (mimeType.


2 Answers

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.

like image 160
BambooleanLogic Avatar answered Sep 30 '22 15:09

BambooleanLogic


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.

like image 27
Durandal Avatar answered Sep 30 '22 16:09

Durandal