改的是PHP的代碼
在admin\controller\Ajax.php文件
找到 上傳文件方法:upload
在該方法下找到這一行:
\think\Hook::listen("upload_after", $attachment);
將下方這些代碼,添加到上面那行代碼的后面
if (in_array($fileInfo['type'], ['image/gif', 'image/jpg', 'image/jpeg', 'image/bmp', 'image/png', 'image/webp']) || in_array($suffix, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'webp'])) { $max_size = 1024 * 400; if ($fileInfo['size'] > $max_size) { $required_memory = $imgInfo[0] * $imgInfo[1] * $imgInfo['bits']; $new_limit = memory_get_usage() + $required_memory + 200000000; ini_set("memory_limit", $new_limit); if ($fileInfo['type'] == 'image/jpg' || $fileInfo['type'] == 'jpg' || $fileInfo['type'] == 'image/jpeg' || $fileInfo['type'] == 'jpeg') { $image = ROOT_PATH . '/public' . $uploadDir . $fileName; $src = @imagecreatefromjpeg($image); $newwidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth; //寬高可以設置, $newheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight; $newwidth = $newwidth / 2; $newheight = $newheight / 2; $tmp = imagecreatetruecolor($newwidth, $newheight); //生成新的寬高 imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $imagewidth, $imageheight); //縮放圖像 $output = imagejpeg($tmp, $image, 30); //第三個參數(0~100);越大越清晰,圖片大小也高; png格式的為(1~9) // ini_restore ("memory_limit"); } else if ($fileInfo['type'] == 'image/png' || $fileInfo['type'] == 'png') { $image = ROOT_PATH . '/public' . $uploadDir . $fileName; $src = @imagecreatefrompng($image); $newwidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth; $newheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight; $newwidth = $newwidth / 2; $newheight = $newheight / 2; $tmp = imagecreatetruecolor($newwidth, $newheight); imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $imagewidth, $imageheight); $output = imagepng($tmp, $image, 3); //這個圖片的第三參數(1~9) // ini_restore ("memory_limit"); } } }
【imagejpeg】和【imageong】方法的第三個參數控制清晰度和大小
代碼解析:
首先判斷 上傳文件是否為圖片類型 ,然后對圖片大小進行判斷, 超過一定大小后進行圖片壓縮,ini_set(“memory_limit”, $new_limit);是自動設置服務器分配給php程序所需要的內存大小,因為在執行png格式大圖片imagecreatefrompng 時會造成內存溢出,ini_restore (“memory_limit”);是為了在執行壓縮后恢復服務器的設置
參考博文地址:https://blog.csdn.net/Shuainan_0619/article/details/107127546
自己做個記錄