Test if a file is an image file

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

    Here's my code based on the answer using tika.

    private static final Tika TIKA = new Tika();
    public boolean isImageMimeType(File src) {
        try (FileInputStream fis = new FileInputStream(src)) {
            String mime = TIKA.detect(fis, src.getName());
            return mime.contains("/") 
                    && mime.split("/")[0].equalsIgnoreCase("image");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    

提交回复
热议问题