问题
I wish to resize an image-file before it is being upload. My idea is, resize the 'temp' file & upload it. But the code gives error. Below I attached my code & comments.
<input type="file" name="file" id="file" required /> <!-- HTML Front-end through which the file would be uploaded-->
php code begins...
$fileName = $_FILES['file']['tmp_name']; //get the uploaded file's name
$ext = strtolower(substr(strrchr(fileName, '.'), 1)); //get the file's extension
$tempFile = $_FILES['file']['tmp_name']; //temporary file's path
$identityNumber="20150816"; //assigns an identity number and...
$targetPath = "uploads/".$identityNumber.'.'.$ext; //rename file & upload it
$image_properties = getimagesize($tempFile);
$image_width = $image_properties[0];
$image_height = $image_properties[1];
$percent = 0.5; //Percentage by which the image is going to be resized
$newWidth = $image_width * $percent;
$newHeight = $image_height * $percent;
if ($ext == "jpeg" || $ext == "jpg") {
header('Content-type: image/jpeg');
$thumb = imagecreatefromjpeg($tempFile);
} elseif ($ext == "png") {
header('Content-type: image/png');
$thumb = imagecreatefrompng($tempFile);
}
$modifiedFile = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled(
$modifiedFile,
$thumb,
0,
0,
0,
0,
$new_width,
$new_height,
$width,
$height
);
And this is the code which gives warning as stated below...
move_uploaded_file($modifiedFile,$targetPath);
Warning: move_uploaded_file() expects parameter 1 to be string, resource given in...
And the 'echo is'
Resource id #10
Why the function move_uploaded_file gives warning..? could anyone help to achieve it?
I know there are several ways to resize the image such as "GD", "ImageMajick" etc. But I prefer the above code only...
回答1:
You can save the file using imagepng
function which, contrary to move_uploaded_file
, accepts resource argument. imagejpeg
function also exists.
imagepng ($modifiedFile, $targetPath);
回答2:
http://us3.php.net/manual/en/function.imagejpeg.php
move_uploaded_file() file used for moving uploaded file from temp folder to destination folder . It works like copy. So It expect both parameters to be strings.
In your case you are create an entirely new image file so you need to use imageXXX() function for writing image to disk. For jpeg image you call imagejpeg() for png you use imagepng() etc.
来源:https://stackoverflow.com/questions/32034263/resize-the-image-file-before-uploading-could-we-overwrite-the-temp-file-uploa