【问题标题】:Check if file is a valid jpg检查文件是否为有效的 jpg
【发布时间】:2013-03-21 04:46:14
【问题描述】:

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

ImageIO.read

我看过例子

String directory="/directory";     

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

我不知道从哪里开始,它需要整个目录......但我需要目录中的每个 jpg 文件。谁能告诉我我的代码有什么问题或需要添加哪些内容?

谢谢!

【问题讨论】:

  • 从那里去哪里取决于你想做什么:)
  • 您可能希望更具体地了解问题所在。代码没有编译,没有做任何事情等吗?从查看代码来看,您似乎只是在注释所在的位置添加了警报或其他内容,如果它不是 jpeg,它将警告您,否则如果它确实是 jpeg,则不会使用 catch 块.
  • @Thihara 已更新。谢谢!
  • @BrianDHall 更新谢谢!
  • 了解如何从 Java 文件中读取字节(二进制,byte [],而不是 String),这是相当多的 101 东西...然后查看字节(jpg 标头)。跨度>

标签: java


【解决方案1】:

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

Example for GIF it will be
GIF87a or GIF89a 

For JPEG 
image files begin with FF D8 and end with FF D9

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();
    }
}

【讨论】:

  • 对于 JPEG,文件以包含段偏移的标头开头。字符“JFIF”actually appear at the start of the APP0 segment.
  • 我尝试了一些 JPEG 文件,但在某些情况下读取的整数是 0xffd8ffe1,所以我认为最好只检查 2 个字节,即 0xFFD8
【解决方案2】:

您需要让阅读器习惯于阅读该格式,并检查没有可用于给定文件的阅读器...

String fileName = "Your image file to be read";
ImageInputStream iis = ImageIO.createImageInputStream(new File(fileName ));
Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("jpg");
boolean canRead = false;
while (readers.hasNext()) {
    try {        
        ImageReader reader = readers.next();
        reader.setInput(iis);
        reader.read(0);
        canRead = true;
        break;
    } catch (IOException exp) {
    }        
}

现在基本上,如果没有一个阅读器可以读取文件,那么它就不是 Jpeg

警告

这仅在有可用于给定文件格式的阅读器时才有效。它可能仍然是 Jpeg,但没有适用于给定格式的阅读器...

【讨论】:

    【解决方案3】:

    改进@karthick 给出的答案,您可以执行以下操作:

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

    【讨论】:

      猜你喜欢
      • 2010-09-20
      • 1970-01-01
      • 2015-11-15
      • 2020-02-10
      • 2015-09-30
      • 2015-09-28
      • 2014-11-15
      • 2010-09-12
      • 1970-01-01
      相关资源
      最近更新 更多