Efficiently detect corrupted jpeg file? Efficiently detect corrupted jpeg file? php php

Efficiently detect corrupted jpeg file?


From the command line you can use jpeginfo to find out if a jpeg file is OK or not.

$ jpeginfo -c test.jpeg

test.jpeg 260 x 264 24bit JFIF N 15332 [OK]

It should be trivial to call jpeginfo from php.


My simplest (and fastest) solution:

function jpeg_file_is_complete($path) {    if (!is_resource($file = fopen($path, 'rb'))) {        return FALSE;    }    // check for the existence of the EOI segment header at the end of the file    if (0 !== fseek($file, -2, SEEK_END) || "\xFF\xD9" !== fread($file, 2)) {        fclose($file);        return FALSE;    }    fclose($file);    return TRUE;}function jpeg_file_is_corrupted($path) {    return !jpeg_file_is_complete($path);}

Note: This only detects a corrupted file structure, but does NOT detect corrupted image data.


FYI -- I've used the method above (jpeg_file_is_complete) to test JPEGs which I know are corrupt (when I load them in a browser, for example, the bottom is gray -- i.e., the image is "cut off"). Anyhow, when I ran the above test on that image it DID NOT detect it as corrupt.

So far, using imagecreatefromjpeg() works, but is not very fast. I found that using jpeginfo works as well to detect these types of corrupt images, and is FASTER than imagecreatefromjpeg (I ran a benchmark in my PHP using microtime()).