本文介绍了如何防止“不是有效的图像文件”在PHP中使用GD函数imagecreatefrom *时出错?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用imagecreatefromgif / imagecreatefromjpeg / imagecreatefromjpeg函数和上传的图像,有时会在图像损坏时出现错误(例如警告:imagecreatefromgif():...不是有效的GIF文件)。我阅读了很多关于这个主题的帖子,找不到工作的答案。

I am using imagecreatefromgif / imagecreatefromjpeg / imagecreatefromjpeg functions with uploaded images and sometimes get an error (e.g. Warning: imagecreatefromgif(): ... is not a valid GIF file) when the image is corrupted. I read lots of posts about this topic and couldn't find a "working" answer.

我确实尝试了以下一些方法来验证图像(如其他人所建议的那样)帖子),但没有一个在所有情况下都有效。如果图像没有标题信息,则以下方法有效,但如果图像具有标题/ mime类型信息且已损坏,则无效。

I did try some of the following to validate the image (as suggested on other posts) but none of them worked in ALL situations. If the image does not have the header info, the following works, but if the image has the header/mime type info and is corrupted, it doesn't work.

if( imagecreatefromjpeg($uploaded_image) !== false ) {
    // image is okay.
}

OR

try {
    $test = imagecreatefrompng($uploaded_image);
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

OR

使用getimagesize($ uploaded_image); //如果图像无效,将返回false或错误。

using getimagesize($uploaded_image); // will return false or an error if image is not valid.

这些情况都不适用于具有标题信息/ mime类型信息的损坏图像文件。

None of those situations worked with a corrupted image file that has the header info/mime type info.

我想防止出现这些错误,如果可能的话,检测图像是否没有损坏,并且可以使用任何imagecreatefromgif / imagecreatefromjpeg / imagecreatefromjpeg函数。如果损坏,我想显示错误消息而不是运行功能。我正在寻找PHP的解决方案。

I would like to prevent having those errors and if possible detect if the image is not corrupted and can be used without problems with any of the imagecreatefromgif / imagecreatefromjpeg / imagecreatefromjpeg functions. If corrupted, I would like to display an error message instead of running the funciton. I am looking for a solution in PHP.

感谢您的帮助和建议。

推荐答案

你可以尝试

$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.

这篇关于如何防止“不是有效的图像文件”在PHP中使用GD函数imagecreatefrom *时出错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 05:39