检查文件是否是有效的jpg

Ted*_*y13 8 java

我想检查我从一个目录中读取的文件是否是jpg,但我不想只是检查扩展名.我在想另一种方法是阅读标题.我做了一些研究,我想用

ImageIO.read
Run Code Online (Sandbox Code Playgroud)

我见过这个例子

String directory="/directory";     

BufferedImage img = null;
try {
   img = ImageIO.read(new File(directory));
} catch (IOException e) {
   //it is not a jpg file
}
Run Code Online (Sandbox Code Playgroud)

我不知道从哪里开始,它需要整个目录...但我需要目录中的每个jpg文件.有人可以告诉我我的代码有什么问题或者需要添加什么?

谢谢!

kar*_*ick 6

您可以读取缓冲图像中存储的第一个字节.这将为您提供确切的文件类型

Example for GIF it will be
GIF87a or GIF89a 

For JPEG 
image files begin with FF D8 and end with FF D9
Run Code Online (Sandbox Code Playgroud)

http://en.wikipedia.org/wiki/Magic_number_(programming)

试试这个

  Boolean status = isJPEG(new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\Chrysanthemum.jpg"));
System.out.println("Status: " + status);


private static Boolean isJPEG(File filename) throws Exception {
    DataInputStream ins = new DataInputStream(new BufferedInputStream(new FileInputStream(filename)));
    try {
        if (ins.readInt() == 0xffd8ffe0) {
            return true;
        } else {
            return false;

        }
    } finally {
        ins.close();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 对于JPEG,文件以包含段偏移的标题开头.字符"JFIF"[实际出现在APP0段的开头](http://en.wikipedia.org/wiki/JPEG_File_Interchange_Format#File_format_structure). (2认同)
  • 我尝试了一些JPEG文件但在某些情况下整数读取是0xffd8ffe1所以我认为最好只检查2个字节,即0xFFD8 (2认同)