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

时间:2018-06-17 13:54:10

标签: php file-upload

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

这是我的代码:

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

1 个答案:

答案 0 :(得分:1)

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