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