基本原理:curl
取原來的圖片,長寬乘以比例,從新生成一張圖片,獲取這張圖片的大小,若是仍是超過預期大小,繼續在此基礎上乘以壓縮比例,生成圖片,直到達到預期ui
1 /** 2 * @獲取遠程圖片的體積大小 單位byte 3 * @date 2016/9/23 4 * @author Jimmy 5 * @param $uri 6 * @param string $user 7 * @param string $pw 8 * @return string 9 */ 10 public static function remoteFilesize($uri, $user='', $pw='') 11 { 12 ob_start(); 13 $ch = curl_init($uri); 14 curl_setopt($ch, CURLOPT_HEADER, 1); 15 curl_setopt($ch, CURLOPT_NOBODY, 1); 16 if (!empty($user) && !empty($pw)) { 17 $headers = array('Authorization: Basic ' . base64_encode($user.':'.$pw)); 18 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 19 } 20 curl_exec($ch); 21 curl_close($ch); 22 $head = ob_get_contents(); 23 ob_end_clean(); 24 $regex = '/Content-Length:\s([0-9].+?)\s/'; 25 preg_match($regex, $head, $matches); 26 return isset($matches[1]) ? $matches[1] : 'unknown'; 27 }
1 /** 2 * @desc 等比例壓縮圖片到指定KB大小 3 * @author Jimmy 4 * @date 2016/9/26 5 * @param $url 遠程圖片地址 6 * @param $maxSize 須要壓縮的最終適合的大小KB 7 * @param $dirPath 文件存放的目錄 8 * @param float $ratio 文件壓縮係數(大於0小於1),該值越大,獲得的壓縮圖片約接近指定的KB大小 9 * @return bool|string 壓縮後文件存放路徑 10 */ 11 public static function compressImageToSize($url,$maxSize,$dirPath,$ratio=0.9){ 12 $fileLength=UtilityHelper::remoteFilesize($url); 13 $originSize=getimagesize($url); 14 $originWidth=$originSize[0]; 15 $originHeight=$originSize[1]; 16 $varWidth = $originWidth; 17 $varHeight = $originHeight; 18 if(!file_exists($dirPath)){ 19 mkdir($dirPath); 20 } 21 $desPath = $dirPath. Uuid::createUuid().'.jpg'; 22 if($fileLength/1024.0>$maxSize){//須要等比例壓縮處理 23 while(true){ 24 $currentWidth = intval($varWidth*$ratio); 25 $currentHeight = intval($varHeight*$ratio); 26 $varWidth = $currentWidth; 27 $varHeight = $currentHeight; 28 //生成縮略圖片 29 $im=imagecreatefromjpeg($url); 30 $tn=imagecreatetruecolor($currentWidth, $currentHeight); 31 imagecopyresampled($tn, $im, 0, 0, 0, 0, $currentWidth, $currentHeight, $originWidth, $originHeight); 32 file_exists($desPath)&&unlink($desPath); 33 imagejpeg($tn, $desPath,100); 34 imagedestroy($tn); 35 $length=filesize($desPath)/1024.0; 36 if($length<$maxSize){ 37 break; 38 } 39 } 40 }else{ 41 file_put_contents($desPath,file_get_contents($url),true); 42 } 43 if(empty($desPath)){ 44 return false; 45 }else{ 46 return $desPath; 47 } 48 }