Issue
after receiving the image from the client , I would like to resize it and then store it . I am using this function:
function PIPHP_ImageResize($image, $w, $h)
{
$oldw = imagesx($image);
$oldh = imagesy($image);
$temp = imagecreatetruecolor($w, $h);
imagecopyresampled($temp, $image, 0, 0, 0, 0,
$w, $h, $oldw, $oldh);
return $temp;
}
$image = PIPHP_ImageResize($_FILES['file']['tmp_name'],10,10);
move_uploaded_file($image, $newname);
unfortunately I got these warning:
- Warning: imagesx() expects parameter 1 to be resource, string given...
- Warning: imagesy() expects parameter 1 to be resource, string given ...
- Warning: imagecopyresampled() expects parameter 2 to be resource, string given ...
- Warning: move_uploaded_file() expects parameter 1 to be string, resource given ...
How could I fix the problem !!
Solution
imagesx
expect an image resource as first parameter. You have to create one using the appropriate function, imagecreatefromjpeg or imagecreatefrompng for example.
function PIPHP_ImageResize($image, $w, $h)
{
$oldw = imagesx($image);
$oldh = imagesy($image);
$temp = imagecreatetruecolor($w, $h);
imagecopyresampled($temp, $image, 0, 0, 0, 0, $w, $h, $oldw, $oldh);
return $temp;
}
if (move_uploaded_file($_FILES['file']['tmp_name'], $newname)) {
$uploadedImage = imagecreatefromjpeg($newname);
if (!$uploadedImage) {
throw new Exception('The uploaded file is corrupted (or wrong format)');
} else {
$resizedImage = PIPHP_ImageResize($uploadedImage,10,10);
// save your image on disk
if (!imagejpeg ($resizedImage, "new/filename/path")) {
throw new Exception('failed to save resized image');
}
}
} else {
throw new Exception('failed Upload');
}
I've added a minimal and insufficient error handling, you should check, for example, the format of the uploaded file and use the appropriate image creator function, or check if the uploaded file is an image.
Addendum
You can determine the type of the presumed uploaded image using getimagesize function.
getimagesize return an array. If the image type is supported the array[2] value return the type of the image. if the file is not an image, or its format is not supported, the array[0] value is zero. Once you know the file format of the image you can use one of the imagecreatefromxxx functions to create the appropriate image.
Answered By - Eineki Answer Checked By - Terry (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.