0

上传后如何检测损坏的图像?

我使用这样的一些代码:

$imageSize = getimagesize($tmp_name);
if(!$imageSize ||  !in_array($imageSize['mime'], $allowMimeType)){
    $this->error = 'Bad Image';
    @unlink($tmp_name);
    return false;
}
$tn = imagecreatetruecolor(80, 80);
switch ($imageSize['mime']){
    case 'image/jpeg':
        $userphoto = imagecreatefromjpeg($tmp_name);// Error 1
    break;
    case 'image/png':
        $userphoto = imagecreatefrompng($tmp_name);// Error 1
    break;
    case 'image/gif':
        $userphoto = imagecreatefromgif($tmp_name);// Error 1
    break;
    case 'image/bmp':
        $userphoto = imagecreatefromwbmp($tmp_name);// Error 1
    break;
    default:
        $this->error = 'unknown image';
        @unlink($tmp_name);
        return false;
    break;
}
imagecopyresampled($tn, $userphoto, 0, 0, 0, 0, 80, 80, $width, $height);// Error 2
imagejpeg($tn,'images/userphoto/'.$this->username.'.jpg',100);
chmod('images/userphoto/'.$this->username.'.jpg', 0777);
@unlink($tmp_name);
USERPROFILE::updatePhotoByUsersId($this->username.'.jpg', $this->users_id);

但有时我会给出 2 个错误串联,

  1. 在有评论的行// Error 1

imagecreatefromwbmp() [href='function.imagecreatefromwbmp'>function.imagecreatefromwbmp]: >'images/userphoto/4ff7db9800871.bmp' 不是有效的 WBMP 文件

imagecreatefromgif() [href='function.imagecreatefromgif'>function.imagecreatefromgif]: >'images/usersphoto/4fe70bb390758' 不是有效的 GIF 文件

  1. 在评论行// Error 2

    imagecopyresampled():提供的参数不是有效的图像资源

我认为它的发生是因为文件在上传过程中损坏。如果我是对的,我该如何解决这个问题?如果不是,原因是什么?

4

1 回答 1

2

在进行任何进一步处理之前,您应该检查getimagesize()的返回值。

如果getimagesize()返回 a FALSE,则表示它已失败并且文件有问题,因此您应该终止。图像通过此检查后,您可以继续处理。

至于为什么会得到supplied argument is not a valid Image resource,解释很简单:很可能,存储的图像$userphoto实际上是FALSE因为imagecreatefrompng()和其他imagecreatefrom功能失败,返回一个FALSE.

getimagesize()解决方案:在继续之前检查上传的图像是否有效。

上传失败的一些可能原因:

  • 将图像写入临时目录时,某些东西会损坏图像。
  • 用户正在上传损坏的文件。

关于imagecreatefromwbmp()失败,这是因为 gd 不支持 BMP 文件。您需要将 BMP 转换为 gd 可以使用的格式。例如,您可以使用bmp2png

于 2012-07-07T09:55:52.190 回答