等比例压缩图片到指定的KB大小

时间:2025-01-27 22:35:50

基本原理:

取原来的图片,长宽乘以比例,重新生成一张图片,获取这张图片的大小,如果还是超过预期大小,继续在此基础上乘以压缩比例,生成图片,直到达到预期

     /**
* @获取远程图片的体积大小 单位byte
* @date 2016/9/23
* @author Jimmy
* @param $uri
* @param string $user
* @param string $pw
* @return string
*/
public static function remoteFilesize($uri, $user='', $pw='')
{
ob_start();
$ch = curl_init($uri);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
if (!empty($user) && !empty($pw)) {
$headers = array('Authorization: Basic ' . base64_encode($user.':'.$pw));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
curl_exec($ch);
curl_close($ch);
$head = ob_get_contents();
ob_end_clean();
$regex = '/Content-Length:\s([0-9].+?)\s/';
preg_match($regex, $head, $matches);
return isset($matches[1]) ? $matches[1] : 'unknown';
}
     /**
* @desc 等比例压缩图片到指定KB大小
* @author Jimmy
* @date 2016/9/26
* @param $url 远程图片地址
* @param $maxSize 需要压缩的最终适合的大小KB
* @param $dirPath 文件存放的目录
* @param float $ratio 文件压缩系数(大于0小于1),该值越大,得到的压缩图片约接近指定的KB大小
* @return bool|string 压缩后文件存放路径
*/
public static function compressImageToSize($url,$maxSize,$dirPath,$ratio=0.9){
$fileLength=UtilityHelper::remoteFilesize($url);
$originSize=getimagesize($url);
$originWidth=$originSize[0];
$originHeight=$originSize[1];
$varWidth = $originWidth;
$varHeight = $originHeight;
if(!file_exists($dirPath)){
mkdir($dirPath);
}
$desPath = $dirPath. Uuid::createUuid().'.jpg';
if($fileLength/1024.0>$maxSize){//需要等比例压缩处理
while(true){
$currentWidth = intval($varWidth*$ratio);
$currentHeight = intval($varHeight*$ratio);
$varWidth = $currentWidth;
$varHeight = $currentHeight;
//生成缩略图片
$im=imagecreatefromjpeg($url);
$tn=imagecreatetruecolor($currentWidth, $currentHeight);
imagecopyresampled($tn, $im, 0, 0, 0, 0, $currentWidth, $currentHeight, $originWidth, $originHeight);
file_exists($desPath)&&unlink($desPath);
imagejpeg($tn, $desPath,100);
imagedestroy($tn);
$length=filesize($desPath)/1024.0;
if($length<$maxSize){
break;
}
}
}else{
file_put_contents($desPath,file_get_contents($url),true);
}
if(empty($desPath)){
return false;
}else{
return $desPath;
}
}