Test if a file is an image file

后端 未结 8 1238
情深已故
情深已故 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:05

    You may try something like this:

       import javax.activation.MimetypesFileTypeMap;
    
       File myFile;
    
       String mimeType = new MimetypesFileTypeMap().getContentType( myFile ));
       // mimeType should now be something like "image/png"
    
       if(mimeType.substring(0,5).equalsIgnoreCase("image")){
             // its an image
       }
    

    this should work, although it doesn't seem to be the most elegant version.

提交回复
热议问题