PbootCMS---优化压缩图片上传
最近在用PbootCMS给客户优化一个功能,原因是这样的:使用PbootCMS给客户做了一个报名系统,需要上传大量的身份证照片,差不多在10万张左右,就会造成服务器内存空间占用量很大,现在优化一个图片压缩的功能。
首先找到PbootCMS的图片上传方法:
位置:admin \ controller \ IndexController.php
具体的upload方法:
增加一个等比压缩图片的方法:compressedImage
具体方法示例:
/** * desription 压缩图片 * @param string $imgsrc 图片路径 * @param string $imgdst 压缩后保存路径,从项目根目录开始的路径(为空则输出图片) * @param string $imgwidth 等比压缩图片 图片的宽度 */ public function compressedImage($imgsrc, $imgdst ,$imgwidth = 800) { list($width, $height, $type) = getimagesize($imgsrc); $newWidth = $width > 800 ? 800 : $width; //图片宽度的限制 $newHeight = $height > 800 ? ceil($height * 800 / $width) : $height; //自适应匹配图片高度 switch ($type) { case 1: #先判断是否为gif动画 $fp = fopen($imgsrc, 'rb'); $image_head = fread($fp, 1024); fclose($fp); $giftype = preg_match("/" . chr(0x21) . chr(0xff) . chr(0x0b) . 'NETSCAPE2.0' . "/", $image_head) ? false : true; if ($giftype) { header('Content-Type:image/gif'); $image_wp = imagecreatetruecolor($newWidth, $newHeight); $image = imagecreatefromgif($imgsrc); imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); //90代表的是质量、压缩图片容量大小 imagejpeg($image_wp, $imgdst, 90); imagedestroy($image_wp); imagedestroy($image); } break; case 2: header('Content-Type:image/jpeg'); $image_wp = imagecreatetruecolor($newWidth, $newHeight); $image = imagecreatefromjpeg($imgsrc); imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); //90代表的是质量、压缩图片容量大小 imagejpeg($image_wp, $imgdst, 90); imagedestroy($image_wp); imagedestroy($image); break; case 3: header('Content-Type:image/png'); $image_wp = imagecreatetruecolor($newWidth, $newHeight); $image = imagecreatefrompng($imgsrc); imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); //90代表的是质量、压缩图片容量大小 imagejpeg($image_wp, $imgdst, 90); imagedestroy($image_wp); imagedestroy($image); break; } }
此等比压缩方法,主要解决的问题是:现在客户上传的身份证照片是1920宽的照片,我们处理的思路是:按照原尺寸进行等比压缩处理。通过测试,能够将500kb左右的图片,压缩到60k左右。
打完收工!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix