imagecreatefromjpeg() : gd-jpeg : JPEG library reports unrecoverable error

This error came from executing this line of code, when uploading an image jpg and then working with it with the PHP GD2 Library:

$im = @imagecreatefromjpeg($file); 
if($im){
    return $im;
}

The problem is that newer versions of PHP result in an unrecoverable error if you reference a wrong file, or non-jpeg file, according to the manual it is supposed to simply return FALSE, but it does not! The fix is easy, but tedious:

You have to check your file type first:

$file_tempname = null;
if (is_uploaded_file($FILE['tmp_name'])) {
    $file_tempname = $FILE['tmp_name'];
}
else{
    exit('Wrong file type');
}

$file_dimensions = getimagesize($file_tempname);
$file_type = strtolower($file_dimensions['mime']);
    
if ($file_type=='image/jpeg'||$file_type=='image/pjpeg'){
    if(imagecreatefromjpeg($file_tempname)){
        $im = imagecreatefromjpeg($file_tempname);
        return $im;	
    } 
}

4 Responses to “imagecreatefromjpeg() : gd-jpeg : JPEG library reports unrecoverable error”

  1. Umair says:

    Hi,

    Best reply i have seen. i have been wondering around 4 hours how to solve this problem. i was copying images form some site whom were saving images in JPG format while in real those images were PNG. so getimagesize told me that what was going on.

    Great post dude.

  2. Amazing workaround. This really helped me to solve a major issue. You can extend it to all types using switch, just sharing back as that will help many more noobs. Thanks again!


    $TempSrc = $_FILES['ImageFile']['tmp_name'];

    $file_dimensions = getimagesize($TempSrc);
    $ImageType = strtolower($file_dimensions['mime']);
    $process = true;

    //Validate file + create image from uploaded file.
    switch(strtolower($ImageType))
    {
    case 'image/png':
    $CreatedImage = imagecreatefrompng($_FILES['ImageFile']['tmp_name']);
    break;
    case 'image/gif':
    $CreatedImage = imagecreatefromgif($_FILES['ImageFile']['tmp_name']);
    break;
    case 'image/jpeg':
    $CreatedImage = imagecreatefromjpeg($_FILES['ImageFile']['tmp_name']);
    break;
    default:
    die('Unsupported File!'); //output error
    }

  3. Matías says:

    This is excelent! Thanks

  4. navitha says:

    really thank you….It’s so helpful for me.. once again thank you so much

Leave a Reply