压缩图像后的PHP - move_uploaded_file

时间:2013-08-19 12:26:26

标签: php upload compression

我在php中有一个上传脚本,它接受一个或多个文件并将它们上传到我的服务器上。我现在正试图在上传之前压缩图像以节省时间和服务器空间。

我的压缩功能和上传功能都可以自行运行,但我无法将两者结合起来。

如果我在没有压缩的情况下进行上传,请参阅:

if (move_uploaded_file($temp, "../images/" . $upload)){

它工作正常,但它试图移动压缩图像而不是像这里的全尺寸:

    // compression
    $compressed = compress_image($temp, $upload, 70);
    //

    if (move_uploaded_file($temp, "../images/" . $compressed)){

完整代码如下:

function getExtension($str) {
    $ext = pathinfo($str, PATHINFO_EXTENSION);
    return $ext;
}

function compress_image($source_url, $destination_url, $quality) {
    $info = getimagesize($source_url);
    if ($info['mime'] == 'image/jpeg'){$image = imagecreatefromjpeg($source_url);}
    else if ($info['mime'] == 'image/gif'){$image = imagecreatefromgif($source_url);}
    else if ($info['mime'] == 'image/png'){$image = imagecreatefrompng($source_url);}
    imagejpeg($image, $destination_url, $quality);
    return $destination_url;
}


foreach ($_FILES["images"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {

        $temp = $_FILES["images"]["tmp_name"][$key];
        $name = $_FILES["images"]["name"][$key];
        $extension = getExtension($name);
        $extension = strtolower($extension);
        $upload = $_POST['name'].'.'.$extension;

        // compression
        $compressed = compress_image($temp, $upload, 70);
        //

        if (move_uploaded_file($temp, "../images/" . $compressed)){
            echo "OK";
        }
        else{
            echo "ERROR";
        }
    }
}

1 个答案:

答案 0 :(得分:0)

文件说明了这一点。

  

如果filename不是有效的上传文件,则不会执行任何操作,并且   move_uploaded_file()将返回FALSE。

我猜它只适用于原始上传文件。为什么不首先move_upload_file然后进行压缩。