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?
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.
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 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With