I need a quick Java way to check if a JPEG file is valid or is it a truncated / damaged image.
I tried to do this in several ways:
using javax.ImageIO library
public boolean check(File image) throws IOException { try { BufferedImage bi = ImageIO.read(image); bi.flush(); } catch (IIOException e) { return false; } return true; }
but it can detect only a few damaged files from those that I tested, and it is very slow (on my computer about 1 image per second).
Apache Commons Image Library
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; } }
This code can detect all corrupted images that I tested, but the performance is very low (on my computer less than 1 image per second).
I am looking for a Java alternative for the UNIX jpeginfo program , which is about 10 times faster (about 10 images per second on my computer).
JPEG, , , EOI ( ) (FF D9) .
EOI
FF D9
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] == -23; // FF D9 } }
, , ...
jpeginfo, , C. , , - ( ++) Java-, .
:
1 , (S) , 2 ( - ).
, , - Java, , 2 , , .
, JPEG , - .
, . . - , SOI EOI .
, , .
Java-, , jpeginfo imagemagick ident - , Java.
- , , Runtime.exec identify -regard-warnings -verbose - stdin , macbook mac 2013 200 ( mp3, 300x300px). , , 1 !
identify -regard-warnings -verbose -
( -verbose imagemagick, )
-verbose