Test if a file is an image file

后端 未结 8 1260
情深已故
情深已故 2020-12-01 07:55

I am using some file IO and want to know if there is a method to check if a file is an image?

8条回答
  •  一个人的身影
    2020-12-01 08:07

    There are a variety of ways to do this; see other answers and the links to related questions. (The Java 7 approach seems the most attractive to me, because it uses platform specific conventions by default, and you can supply your own scheme for file type determination.)

    However, I'd just like to point out that no mechanism is entirely infallible:

    • Methods that rely on the file suffix will be tricked if the suffix is non-standard or wrong.

    • Methods that rely on file attributes (e.g. in the file system) will be tricked if the file has an incorrect content type attribute or none at all.

    • Methods that rely on looking at the file signature can be tricked by binary files which just happen to have the same signature bytes.

    • Even simply attempting to read the file as an image can be tricked if you are unlucky ... depending on the image format(s) that you try.

提交回复
热议问题