在上传之前调整图像文件的大小;我们可以覆盖临时文件吗?上传? [英] Resize the image-file before uploading; Could we overwrite the temp file & upload?

查看:98
本文介绍了在上传之前调整图像文件的大小;我们可以覆盖临时文件吗?上传?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在上传图像文件之前调整其大小.我的想法是调整临时"文件的大小,上载它.但是代码给出了错误.下面我附上我的代码&评论.

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代码开始...

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
);

这是发出警告的代码,如下所述... move_uploaded_file($modifiedFile,$targetPath);

And this is the code which gives warning as stated below... move_uploaded_file($modifiedFile,$targetPath);

警告:move_uploaded_file()期望参数1为字符串,资源在...中给出

Warning: move_uploaded_file() expects parameter 1 to be string, resource given in...

回声是"

资源ID#10

Resource id #10

为什么函数move_uploaded_file发出警告..?有人可以帮助实现它吗?

Why the function move_uploaded_file gives warning..? could anyone help to achieve it?

我知道有几种方法可以调整图像的大小,例如"GD","ImageMajick"等.但是我只喜欢上面的代码...

I know there are several ways to resize the image such as "GD", "ImageMajick" etc. But I prefer the above code only...

推荐答案

您可以使用imagepng函数保存文件,与move_uploaded_file相反,该函数接受资源参数. imagejpeg功能也存在.

You can save the file using imagepng function which, contrary to move_uploaded_file, accepts resource argument. imagejpeg function also exists.

imagepng ($modifiedFile, $targetPath);

这篇关于在上传之前调整图像文件的大小;我们可以覆盖临时文件吗?上传?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆