Imagecreatefromjpeg returns a black image after resize
I have a script to resize an uploaded image, but when I use it, it just returns a black square. All error messages are poin开发者_如何学Pythonting at this function:
function resizeImage($image,$width,$height,$scale) {
$newImageWidth = ceil($width * $scale);
$newImageHeight = ceil($height * $scale);
$newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
$source = imagecreatefromjpeg($image);
imagecopyresampled($newImage,$source,0,0,0,0,$newImageWidth,$newImageHeight,$width,$height);
imagejpeg($newImage,$image,90);
chmod($image, 0777);
return $image;
}
My error logs:
PHP Warning: imagecreatefromjpeg() [<a href='function.imagecreatefromjpeg'>function.imagecreatefromjpeg</a>]: gd-jpeg: JPEG library reports unrecoverable error
PHP Warning: imagecreatefromjpeg() [<a href='function.imagecreatefromjpeg'>function.imagecreatefromjpeg</a>]: 'img/[hidden].jpg' is not a valid JPEG file
PHP Warning: imagecopyresampled(): supplied argument is not a valid Image resource
According to Marc B's answer you could probably make a check if the file is a JPG file. (JPEG, JPG, jpg, jpeg extensions).
it could be something like:
$file = explode(".", $_POST['file']);
$file_ext = $file[count($file)]; // Get the last thing in the array - in this way the filename can containg dots (.)
$allowed_ext = array('jpg', 'JPG', 'jpeg', 'jpg');
if( in_array($file_ext, $allowed_ext )
{
// The code for creating the image here.
}
- Check if the
imagecreatetruecolor
succeeded. If the new image is "large" it could exceed the PHP memory_limit. This function returns FALSE if it failed for any reason. - Ditto with
imagecreatefromjpeg()
. The two individual images may fit within the memory limit but together could be too large. The source image may also not exist. This function returns FALSE if it failed for any reason - Check if the
imagecopyresampled()
failed - it also returns FALSE on failure. - Check if
imagejpeg()
failed - maybe you don't have write permissions on whatever file you're specifying in$image
. And again, this function returns FALSE on failure.
精彩评论