且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何防止“不是有效的图像文件”在PHP中使用GD函数imagecreatefrom *时出错?

更新时间:2023-11-25 17:31:16

你可以尝试

$gd = @imagecreatefromstring(file_get_contents($file_path));    
    if ($gd === false) {
        throw new Exception ('Image is corrupted');
    }

它应该适用于gd已知的大多数图像格式。此外,如果您需要特定的错误消息,可以使用error_get_last()。

It should work with most image formats known to gd. Also if you need specific error message you can use error_get_last().

@将禁止错误消息,imagecreatefromstring尝试打开已知的图像格式。如果失败,$ gd将具有值'false'并且不会抛出任何错误消息。

@ will suppress error messages, and imagecreatefromstring tries to open known image formats. If this fails, $gd will have value 'false' and no error messages are thrown.

编辑:

请注意,在这个例子中,@ operator也会从file_get_contents函数中获取任何错误。

Please not that in this example @ operator also will suprpess any errors from file_get_contents function.