'How to check a uploaded file whether it is an image or other file?

In my web application I have an image uploading module. I want to check the uploaded file whether it's an image file or any other file. I am using Java in server side.

The image is read as BufferedImage in java and then I am writing it to disk with ImageIO.write()

How shall I check the BufferedImage, whether it's really an image or something else?

Any suggestions or links would be appreciated.



Solution 1:[1]

I used org.apache.commons.imaging.Imaging in my case. Below is a sample piece of code to check if an image is a jpeg image or not. It throws ImageReadException if uploaded file is not an image.

    try {
        //image is InputStream
        byte[] byteArray = IOUtils.toByteArray(image);
        ImageFormat mimeType = Imaging.guessFormat(byteArray);
        if (mimeType == ImageFormats.JPEG) {
            return;
        } else {
            // handle image of different format. Ex: PNG
        }
    } catch (ImageReadException e) {
        //not an image
    }

Solution 2:[2]

This is built into the JDK and simply requires a stream with support for

byte[] data = ;
InputStream is = new BufferedInputStream(new ByteArrayInputStream(data));
String mimeType = URLConnection.guessContentTypeFromStream(is);
//...close stream

Solution 3:[3]

Try using multipart file instead of BufferedImage

import org.apache.http.entity.ContentType;
...

    public void processImage(MultipartFile file) {

       if(!Arrays.asList(ContentType.IMAGE_JPEG.getMimeType(), ContentType.IMAGE_PNG.getMimeType(), ContentType.IMAGE_GIF.getMimeType()).contains(file.getContentType())) {
            throw new IllegalStateException("File must be an Image");
                 }
      }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gagan bopanna
Solution 2 gcstang
Solution 3