fastadmin 后台自带ajax上传图片php压缩

改的是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

自己做个记录

posted @ 2020-12-03 17:46  贱贱丶  阅读(977)  评论(0编辑  收藏  举报