the dreaded "Warning: imagecreatefromjpeg() : '/tmp/filename' is not a valid JPEG file in /phpfile.php on line xxx"

I've been getting this warning when some people upload images to our site :

Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: gd-jpeg: JPEG library reports unrecoverable error: in /home/pathremoved/includes/snapsutils.php on line 220

Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: '/tmp/phpiw4MFk' is not a valid JPEG file in /home/pathremoved.php on line 220

Warning: imagesx(): supplied argument is not a valid Image resource in /home/pathremoved.php on line 222

Warning: imagesy(): supplied argument is not a valid Image resource in /home/pathremoved.php on line 223

Warning: imagecreatetruecolor() [function.imagecreatetruecolor]: Invalid image dimensions in /home/pathremoved.php on line 240

Warning: imagecopyresampled(): supplied argument is not a valid Image resource in /home/pathremoved.php on line 242

This only happens with certain images, which when opened in any program are ok, it even uploads to the version of the site I have on localhost with no problems...I googled a bit but found nothing conclusive...

note php upload_max size is 5M and post_max_size is 5M. This is not an upload or memory issue. I've tested with 4M images without problems.

any help appreciated.


After a little digging around on Google I found this bug report. It seems that the GD library is less tolerant of buggy JPEG files than other programs. The solution suggested was to set GD to ignore JPEG error's before processing the image, like this:

ini_set("gd.jpeg_ignore_warning", 1);

Hopefully that will work for you. One other potential problem you may run into is to do with memory. It seems that GD holds all images in memory as bitmaps once they've been opened. This means that a 5MB image can actually consume more memory than a single PHP thread is allowed, resulting in a fatal error. I had this problem with some image uploads and had to reduce the maximum file size I allowed to get around the problem.

Good luck and hope that helps.


I also face same issue.

we used below code to fix this issue and it works for me,

...
$image = @ImageCreateFromJpeg($image_name);
if (!$image)
{
   $image= imagecreatefromstring(file_get_contents($image_name));
}
...

Hope this helps you...:)