3
try{
  $src = imagecreatefromjpeg('https://graph.facebook.com/'.$jsonfriends["data"][$randf]["id"].'/picture');
} catch (Exception $z){
  $src = imagecreatefromgif('https://graph.facebook.com/'.$jsonfriends["data"][$randf]["id"].'/picture');
}

In the above code, when the code in the 'try' block fails, the control is not passing to the 'catch' block. I'm getting output as error as https://graph.facebook.com/xxxxxx/picture is not a valid JPEG. Actually, if its not a JPEG, it would be GIF in this context. So can anyone help me regarding this?

Mihai Oprea
  • 2,051
  • 3
  • 21
  • 39
Mahesh
  • 603
  • 1
  • 10
  • 22
  • possible duplicate of [Problem using imagecreatefromjpeg and imagejpeg](http://stackoverflow.com/questions/1948561/problem-using-imagecreatefromjpeg-and-imagejpeg) – ifaour May 14 '11 at 20:11

1 Answers1

9

imagecreatefromjpeg doesn't throw an exception if it fails. For more information on that, see PHP: How to manage errors gracefully?.

You'd be better off using a function mentioned in the comments of the PHP documentation of the function:

function open_image ($file) {
    $size = getimagesize($file);
    switch($size["mime"]){
        case "image/jpeg":
            $im = imagecreatefromjpeg($file); //jpeg file
            break;
        case "image/gif":
            $im = imagecreatefromgif($file); //gif file
            break;
        case "image/png":
            $im = imagecreatefrompng($file); //png file
            break;
        default: 
            $im=false;
            break;
    }
    return $im;
}

This way, you avoid the problem altogether, as it simply doesn't try to parse the file as a JPEG if it isn't one.

Community
  • 1
  • 1
Sebastian Paaske Tørholm
  • 49,493
  • 11
  • 100
  • 118