测试文件是否为图像文件

2022-09-01 03:25:18

我正在使用一些文件,想知道是否有一种方法可以检查文件是否是图像?IO


答案 1

这对我来说很好。希望我能帮忙

import javax.activation.MimetypesFileTypeMap;
import java.io.File;
class Untitled {
    public static void main(String[] args) {
        String filepath = "/the/file/path/image.jpg";
        File f = new File(filepath);
        String mimetype= new MimetypesFileTypeMap().getContentType(f);
        String type = mimetype.split("/")[0];
        if(type.equals("image"))
            System.out.println("It's an image");
        else 
            System.out.println("It's NOT an image");
    }
}

答案 2
if( ImageIO.read(*here your input stream*) == null)
    *IS NOT IMAGE*    

还有一个答案:如何检查上传的文件是图像还是其他文件?