我需要一种快速的 Java 方法来检查 JPEG 文件是否有效或者它是否是截断/损坏的图像。
我尝试了几种方法:
使用 javax.ImageIO 库
public boolean check(File image) throws IOException { try { BufferedImage bi = ImageIO.read(image); bi.flush(); } catch (IIOException e) { return false; } return true; }
但在我测试过的文件中,它只能检测到少数损坏的文件,而且速度非常慢(在我的 PC 上大约每秒 1 个图像)。
-
public boolean check(File image) throws IOException { JpegImageParser parser = new JpegImageParser(); ByteSourceFile bs = new ByteSourceFile(image); try { BufferedImage bi = parser.getBufferedImage(bs, null); bi.flush(); return true; } catch (ImageReadException e) { return false; } }
此代码可以检测到我测试过的所有损坏图像,但性能非常差(在我的 PC 上低于 1 个图像/秒)。
我正在寻找 UNIX 程序的 Java 替代品 jpeginfo 大约快 10 倍(在我的 PC 上大约每秒 10 张图像)。
最佳答案
我看了一下 JPEG format ,根据我的理解,两个字节 (FF D9
) 的最终 EOI
(图像结束)段应该放在最后。
boolean jpegEnded(String path) throws IOException {
try (RandomAccessFile fh = new RandomAccessFile(path, "r")) {
long length = fh.length();
if (length < 10L) { // Or whatever
return false;
}
fh.seek(length - 2);
byte[] eoi = new byte[2];
fh.readFully(eoi);
return eoi[0] == -1 && eoi[1] == -39; // FF D9 (first falsely -23)
}
}
关于java - 在 Java 中检查损坏的 JPEG 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29609736/