如何将1个图像上传到2个不同的文件夹并调整其大小

时间:2016-06-13 22:03:13

标签: php

我想知道如何将一个图像上传到2个不同的文件夹。让我举个例子:

我想上传1张图片。当我上传图像时,系统会将图像调整为2种不同的分辨率,分辨率为400x400的肖像和分辨率为1200x1200的横向。调整大小后,分辨率为400x400的已调整大小的图像将存储在 portrait 文件夹中,另一个图像将存储在文件夹 landscape 中。我仍然很困惑如何制作那种逻辑。

<?php 

    //This is the directory where images will be saved 
    $target = "uploads/potrait/"; 
    $target = $target . basename( $_FILES['photo']['name']); 
    $target2="uploads/landscape/";
    $target2 = $target2 . basename( $_FILES['photo']['name']);

     //This gets all the other information from the form 
      $test=$_POST['test']; 
      $desc=$_POST['desc'];
      $pic=($_FILES['photo']['name']);
      $loc=$_POST['location'];


     // Connects to your Database 
     mysql_connect("localhost", "root", "") or die(mysql_error()) ;
     mysql_select_db("selfie") or die(mysql_error()) ; 

     $filename = mysql_real_escape_string($_FILES['photo']['name']);
     //Writes the information to the database 
     mysql_query("INSERT INTO image_upload (category, description,image ,location)     VALUES     ('$test', '$desc','$pic','$loc')"); 


     //Writes the photo to the server 
     if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
     { 

     copy($target, $target2);
     } 
     else { 

     //Gives and error if its not 
     echo "Sorry, upload failed."; 
     } 
      ?>

1 个答案:

答案 0 :(得分:0)

这是图像调整大小功能的样子:

function save_resized_image($file_in, $file_out, $new_w, $new_h)
{
    list($w, $h, $type) = getimagesize($file_in);

    switch ($type) {
        case IMG_JPG: $src = imagecreatefromjpeg($file_in); break;
        case IMG_GIF: $src = imagecreatefromgif ($file_in); break;
        case IMG_PNG: $src = imagecreatefrompng ($file_in); break;
        default:
            return false;
    }

    $tmp = imagecreatetruecolor($new_w, $new_h);
    imagecopyresampled($tmp, $src, 0, 0, 0, 0, $new_w, $new_h, $w, $h);

    switch ($type) {
        case IMG_JPG: imagejpeg($tmp, $file_out); break;
        case IMG_GIF: imagegif ($tmp, $file_out); break;
        case IMG_PNG: imagepng ($tmp, $file_out); break;
    }
    return true;
}

你可以像这样使用它:

$basename = basename($_FILES['photo']['name']);
$tmp_name = $_FILES['photo']['tmp_name'];

save_resized_image($tmp_name, "portrait/$basename", 400, 400);
save_resized_image($tmp_name, "landscape/$basename", 1200, 1200);

此功能无法处理图像宽高比。但是我把它留给你了。

注意:此处不需要move_uploaded_file