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

打完收工!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章