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,
- at lines that have comment
// 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
- at line of comment
// Error 2imagecopyresampled(): supplied argument is not a valid Image resource
I think its occurs because the file has damaged during uploading. If i’m right, how i can solve this problem? If not, What is the reason?
Before you do any further processing, you should check the return value of getimagesize() .
If
getimagesize()returns aFALSE, 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$userphotois actuallyFALSEbecauseimagecreatefrompng()and otherimagecreatefromfunctions have failed, returning aFALSE.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.