1

我在 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";
        }
    }
}
4

1 回答 1

0

the documentation says that.

If filename is not a valid upload file, then no action will occur, and move_uploaded_file() will return FALSE.

i am guessing that it will only work on the original upload file. why don't you first move_upload_file and then do the compression.

于 2013-08-19T12:30:00.200 回答