Php 上载图像,调整其大小,重命名并将其移动到目录

Php 上载图像,调整其大小,重命名并将其移动到目录,php,file-upload,Php,File Upload,我试图上传一个图像,调整它的大小,重命名它,并将其移动到一个目录,但出现了一些问题。重新调整文件大小并重命名文件后,我无法将其移动到目录。我只能将原始文件或刚重命名但未调整大小的文件移动到目录中 这是我的代码: $file=$_FILES['file']['name']; $tmp_file=$_FILES['file']['tmp_name']; $size=$_FILES['file']['size']; switch(strtolower($_FILES['file']['type'])

我试图上传一个图像,调整它的大小,重命名它,并将其移动到一个目录,但出现了一些问题。重新调整文件大小并重命名文件后,我无法将其移动到目录。我只能将原始文件或刚重命名但未调整大小的文件移动到目录中

这是我的代码:

$file=$_FILES['file']['name'];
$tmp_file=$_FILES['file']['tmp_name'];
$size=$_FILES['file']['size'];

switch(strtolower($_FILES['file']['type']))
{
    case 'image/jpeg':
        $image = imagecreatefromjpeg($_FILES['file']['tmp_name']);
        break;
    case 'image/png':
        $image = imagecreatefrompng($_FILES['file']['tmp_name']);
        break;
    case 'image/gif':
        $image = imagecreatefromgif($_FILES['file']['tmp_name']);
        break;
    default:
        exit('Unsupported type: '.$_FILES['file']['type']);
}
$max_width = 194;
$max_height = 160;

// Get current dimensions
$old_width  = imagesx($image);
$old_height = imagesy($image);

// Calculate the scaling we need to do to fit the image inside our frame
$scale      = min($max_width/$old_width, $max_height/$old_height);

// Get the new dimensions
$new_width  = ceil($scale*$old_width);
$new_height = ceil($scale*$old_height);
// Create new empty image
$new = imagecreatetruecolor($new_width, $new_height);

// Resize old image into new
imagecopyresampled($new, $image, 
    0, 0, 0, 0, 
    $new_width, $new_height, $old_width, $old_height);
ob_start();
imagejpeg($new, NULL, 90);
$data = ob_get_clean();
imagedestroy($image);
imagedestroy($new);

$file1 = explode(".", $data);
$newfilename = "product_".$r . $file1;

$upload_path1="../upload/items/".basename($newfilename);
if(file_exists($upload_path1)){
echo '<div class="redalert">already exist</div>'; 
} else { 
$upload=move_uploaded_file($data,$upload_path1); 
}

本哈科已经提出了正确的解决方案。但它仍然不起作用,因为您分解了原始数据,并将结果数组用作文件名。此处的文件名应为字符串。还有一个未定义的变量$r

因此,正确的解决方案是:

$ext = pathinfo($file, PATHINFO_EXTENSION);
$newfilename = "product".md5(uniqid("") . time()).'.'.$ext;//to make file name unique
file_put_contents('upload/items/'.$newfilename, $data);

move_Upload_file需要一个tmp文件,而您正在向它提供原始数据,我将尝试使用file_put_内容。编辑:您可以使用imagejpg中的第二个参数将图像保存到文件中。可验证的$r是我放在product之后的唯一数字,因此它类似于product_1、product_2等。。。使用file_put_contents,它可以移动文件,但现在它不再像我用$max_width=194定义的那样调整大小$最大高度=160;,移动到目录的图像变为宽度-120,高度-160…@tyrlaka,用305×335图像大小检查它,它变为148×160。如果希望最大宽度为194,则更改最小$max\u width/$old\u width、$max\u height/$old\u height;至最大$max_width/$old_width、$max_height/$old_height;