Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiently detect corrupted jpeg file?

Is there an efficient way of detecting if a jpeg file is corrupted?

Background info:
  solutions needs to work from within a php script
  the jpeg files are on disk
  manual checking is no option (user uploaded data)

I know that imagecreatefromjpeg(string $filename); can do it. But it is quite slow at doing so.

Does anybody know a faster/more efficient solutions?

like image 776
Jacco Avatar asked Oct 13 '08 17:10

Jacco


People also ask

How do you check if an image is corrupted?

The only way to check if file is corrupted is to try reading it as it is described in file format, ie. load BMP as BMP with reading BMP header, BMP data etc. There are many web pages that describe graphics file formats.

Why are my JPEG files corrupted?

The image files are quite vulnerable to external attacks from any virus or malware, as a small change in the format or header can corrupt them easily. If there is corruption in the hard-drive sector where the JPEG file is saved, then the JPEG is also bound to have effects of the corruption.

How can I open a corrupted JPEG file online?

How to use JPEG repairing app to repair your JPEG file. Click inside the file drop area to upload a file or drag & drop a file. Your file will be uploaded and we'll show you file's defects with preview. Download link of repaired file will be available instantly after repaired.


2 Answers

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.

like image 99
Pat Avatar answered Oct 04 '22 22:10

Pat


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.

like image 20
fireweasel Avatar answered Oct 04 '22 20:10

fireweasel