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



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

这是我的代码:

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

Benjaco已经说出了更正的解决方案。但它仍然不起作用,因为您分解了原始数据并使用生成的数组作为文件名。此处的文件名应为字符串。还有一个未定义的变量$r

所以正确的解决方案是:

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

最新更新