2011-05-14 67 views
2
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'); 
} 

在上面的代码中,当'try'块中的代码失败时,控件不会传递到'catch'块。由于https://graph.facebook.com/xxxxxx/picture不是有效的JPEG,因此我得到的输出为错误。实际上,如果它不是JPEG,在这种情况下它将是GIF。那么有谁能帮我解决这个问题吗?如何正确使用Try-Catch异常?

+0

[使用imagecreatefromjpeg和imagejpeg问题]的可能重复(http://stackoverflow.com/questions/1948561/problem-using-imagecreatefromjpeg-and-imagejpeg) – ifaour 2011-05-14 20:11:21

回答

5

imagecreatefromjpeg如果失败则不会抛出异常。欲了解更多信息,请参阅PHP: How to manage errors gracefully?

你会更好使用功能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; 
} 

这样,你完全避免这个问题,因为它根本不会尝试解析该文件为JPEG,如果它不是一。

+0

非常感谢!!!!它的工作。 – Mahesh 2011-05-15 06:44:39