alex_t
alex_t

Reputation: 103

Determine in Java, whether a file is a picture, having only binary data

The situation is this: in my code I download a picture from the Internet as an array of bytes: byte[] imageBytes. And then I make the object of my MyImage class:

public class MyImage {

    private String imageName;
    private byte[] data;

    // Constructor, getters, setters
}

Create object:

MyImage myimg = new MyImage("some_name", imageBytes);

Then I use my resulting object.

I have a question: can I somehow make sure, that I downloaded the picture file?

It seems that each file type has its own signature (that is, the first bytes of the file). But there are a lot of different types of files. And if I compare the signature of my file with all existing types of signatures, then these will be very large checks.

Is it possible to make the check simpler: do I currently have an image (no matter what type) or not image?

Why do I want to do this: what if the user mistakenly passes a link not to an image, but to a file of a different type (for example, an archive). And in this case, I would like to determine in the code that the wrong file was downloaded and give the user an appropriate error message.

Upvotes: 0

Views: 1249

Answers (1)

queeg
queeg

Reputation: 9372

One way could be to check the Content-Type header that is sent from the server you download from. Another one could be the same algorithm that is used by the Linux file command. It would be tedious to reimplement that in Java.

So I suggest to either

  • check the Content-Type header
  • assuming you are on a *nix system: store the data in a file, then exec file and get the result
  • just try to parse the image and let the graphics library decide. If successful, check the image you obtained
  • some libraries are listed in How to reliably detect file types?
  • The most promising way would be to ask the JDK via probeContentType()

Upvotes: 2

Related Questions