【发布时间】:2023-11-13 02:39:01
【问题描述】:
我已经研究过诸如此类的先前问题的答案,但我没有运气。我的代码工作正常,但它上传了原始文件大小,我想在不改变原始高度和宽度的情况下压缩文件大小(例如从 600kb 到至少 200kb)。我已经尝试过从同一问题给出的答案,但我得到的是缩略图大小(8.0kb),并且上传的图像变成了纯黑色图像。
请帮助我如何使用我目前拥有的图片上传代码来做到这一点。非常感谢!
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
// this assumes that the upload form calls the form file field "file"
$name = $_FILES["file"]["name"];
$type = $_FILES["file"]["type"];
$size = $_FILES["file"]["size"];
$tmp = $_FILES["file"]["tmp_name"];
$error = $_FILES["file"]["error"];
$savepath = "gallery/";
$filelocation = $savepath.$name;
$newfilename = $savepath.$ign;
// Check image file dimensions first and then file size
list($width, $height) = getimagesize($tmp);
if($width > "800" || $height > "600") {
echo "Error: Image size must be a maximum of 800 x 600 pixels.";
}
else if ($size > 500000) {
echo "Error: Image file must be a maximum of 500KB only.";
}
// This won't upload if there was an error or if the file exists, hence the check
if (!file_exists($filelocation) && $error == 0) {
$album = escape_sql(CleanUp($_POST['album']));
$caption = escape_sql(CleanUp($_POST['caption']));
$privacy = escape_sql(CleanUp($_POST['privacy']));
// echo "The file $filename exists";
// This will overwrite even if the file exists
$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = "gallery/".$album."/".$ign.".".$extension;
move_uploaded_file($tmp,$newfilename);
date_default_timezone_set('Asia/Manila');
$date = date('Y-m-d');
$timestamp = strtotime($date);
mysqli_query($connect, "INSERT INTO `gallery` (`id`,`ign`,`album`,`privacy`,`caption`,`filename`,`timestamp`) VALUES ('','$user','$album','$privacy','$caption','$newfilename','$date')");
echo '<h1>My Photos ❱ <i>Uploaded</i></h1>';
echo '<p>Your photo has been uploaded successfully to the '.$album.' album.</p>';
}
else {
unlink($filelocation);
move_uploaded_file($tmp, $filelocation);
echo '<h1>My Photos ❱ <i>Error</i></h1>';
echo '<p>An error has occurred and your photo was not uploaded to the gallery.';
}
【问题讨论】:
-
我在这里看不到任何尝试调整大小的代码...
-
查看这里以获得纯 php 解决方案。 *.com/a/12557415/5873008
-
@AlexHowansky,是的,没有,因为那是我拥有的原始代码。我不确定将调整大小的代码放在哪里,或者什么是正确的代码来调整大小。
-
有很多库可以让您轻松调整大小。
标签: php