PHP 图像上传压缩不起作用.你能看看我的代码吗?



你们是我最后的手段。我已经解决这个问题一天多了,但仍然找不到解决方案。我在下面列出的代码工作正常。它将重命名的图像上传到正确的目录。唯一不起作用的是它不会压缩图像。新图像的文件大小与原始图像的大小完全相同。

我想知道您是否可以看看下面的代码,看看您是否可以发现我做得不对的地方?

我有一个图像压缩代码,是从我在这个网站和其他网站上看到的例子中借来的。就是这样。

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

这是我的图片上传脚本。

if(isset($_FILES['fileToUpload']) AND !empty($_FILES['fileToUpload']["name"])) {
if(is_uploaded_file($_FILES['fileToUpload']["tmp_name"])) {
$target_dir	   = '../members/images/'.$global_user_id.'/projects/'.$url_project_id.'/';
$target_file   = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$source_file   = $_FILES["fileToUpload"]["tmp_name"];
$random_name   = generateRandomString(10);
$new_image     = $random_name . '.' . $imageFileType;
$resized_image = compress_image($source_file, $new_image, 75);
$new_file_path = $target_dir . $resized_image;
if(!is_dir($target_dir)){
mkdir($target_dir, 0775, true);
}
$uploadOk      = 1;
// Check if image file is a actual image or fake image
$check = getimagesize($source_file);
if($check !== false) {
//   echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
$errors[] = 'File is not an image!';
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file)) {
$errors[] = 'Sorry, file already exists!';
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 5000000) {
$errors[] = 'Sorry, your file size is bigger than 5mb!';
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" && $imageFileType != "JPG" && $imageFileType != "PNG" && $imageFileType != "JPEG" && $imageFileType != "GIF") {
$errors[] = 'Sorry, only JPG, JPEG, PNG & GIF files are allowed!';
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if($uploadOk == 0) {
$errors[] = 'Sorry, your file was not uploaded!';
// if everything is ok, try to upload file
} else {
if(move_uploaded_file($source_file, $new_file_path)) {
echo 'success';
} else {
$errors[] = 'Sorry, there was an error uploading your file!';
}
}
} else {
$errors[] = 'You must upload an image!';
}
}

这一行是问题所在:

if(move_uploaded_file($source_file, $new_file_path)) {

您正在移动原始文件。您应该移动$new_image

if(rename($new_image, $new_file_path)) {

最新更新