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左右。

打完收工!

posted @ 2023-03-14 14:29  帅到要去报警  阅读(323)  评论(0编辑  收藏  举报