How i can detect spoiled images after upload?
Im using some code like this:
$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);
But some time i give 2 error tandem,
// Error 1
imagecreatefromwbmp() [href='function.imagecreatefromwbmp'>function.imagecreatefromwbmp]: >'images/userphoto/4ff7db9800871.bmp' is not a valid WBMP file
imagecreatefromgif() [href='function.imagecreatefromgif'>function.imagecreatefromgif]: >'images/usersphoto/4fe70bb390758' is not a valid GIF file
// Error 2
imagecopyresampled(): supplied argument is not a valid Image resource
Before you do any further processing, you should check the return value of getimagesize() .
If getimagesize()
returns a FALSE
, that means it has failed and something is wrong with the file, so you should terminate. Once the image passes this check, you can continue with your processing.
As for why you are getting supplied argument is not a valid Image resource
, the explaination is simple: Most likely, the image stored in $userphoto
is actually FALSE
because imagecreatefrompng()
and other imagecreatefrom
functions have failed, returning a FALSE
.
Solution: Check that the uploaded image is valid with getimagesize()
before continuing.
Some possible reasons as to why the uploads are failing:
Regarding imagecreatefromwbmp()
failing, it is because gd does not support BMP files. You need to convert the BMP into a format gd can work with. For example, you can use bmp2png.