php 图片质量压缩 转

转自:https://blog.csdn.net/qq_41445224/article/details/97402427

php实现图片压缩,可以设置只压缩质量,不改变宽高,也可以设置改变宽高,压缩比是自定义的
/**
* 调用部分
* $url:图片路径 $dst_img:图片保存路径及保存的文件名 $quality:图片的质量 为数字 越小图片的大小就越小
*/

$url = '图片路径';
$dst_img = '图片保存路径 如:./img/test.jpg'; //如果跟$url一样则相当于替换掉原图片
$quality = 75; //图片质量压缩比 0-100 越大图片质量越大 图片的大小也越大 默认为75
//执行调用
compressed_image($url, $dst_img, $quality);

/**
* desription 判断是否gif动画
* @param sting $image_file图片路径
* @return boolean t 是 f 否
*/
function check_gifcartoon($image_file){
$fp = fopen($image_file,'rb');
$image_head = fread($fp,1024);
fclose($fp);
return preg_match("/".chr(0x21).chr(0xff).chr(0x0b).'NETSCAPE2.0'."/",$image_head)?false:true;
}

/**
* desription 压缩图片
* @param sting $imgsrc 图片路径
* @param string $imgdst 压缩后保存路径
* * @param int $quality 图片质量
*/
function compressed_image($imgsrc,$imgdst, $quality){
list($width,$height,$type)=getimagesize($imgsrc);

//这里如果写的是图片大小不变 如果要改变图片大小,如:$new_width = $width * 0.5; 宽度减少一半
$new_width = $width;
$new_height =$height;
switch($type){
case 1:
$giftype = check_gifcartoon($imgsrc);
if($giftype){
header('Content-Type:image/gif');
$image_wp=imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromgif($imgsrc);
imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
//$quality代表的是质量、压缩图片容量大小
imagejpeg($image_wp, $imgdst,$quality);
imagedestroy($image_wp);
}
break;
case 2:
header('Content-Type:image/jpeg');
$image_wp=imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($imgsrc);
imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
//$quality代表的是质量、压缩图片容量大小
imagejpeg($image_wp, $imgdst,$quality);
imagedestroy($image_wp);
break;
case 3:
header('Content-Type:image/png');
$image_wp=imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefrompng($imgsrc);
imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
//$quality代表的是质量、压缩图片容量大小
imagejpeg($image_wp, $imgdst,$quality);
imagedestroy($image_wp);
break;
}
}

点赞

发表回复

电子邮件地址不会被公开。必填项已用 * 标注