简述:
使用php的GD库可以将图片按固定宽高或者等比例压缩,主要利用的函数是:
imagecopyresampled:将一张图片中的一块区域复制到另一张图片上
等比例压缩
public function compressImg($src = '', $percent = 1){list($width, $height, $type, $attr) = getimagesize($src);$type = image_type_to_extension($type, false); $fun = "imagecreatefrom" . $type; $image = $fun($src); $new_width = $width * $percent; $new_height = $height * $percent; $thump = imagecreatetruecolor($new_width, $new_height); //将原图复制到另一张图片上,并且按照一定比例压缩 imagecopyresampled($thump, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); imagedestroy($image); $image = $thump; // 1、浏览器直接输出 header('Content-Type: image/' . $type); $funcs = "image" . $type; $funcs($thump); // 2、保存到对应路径 $path = 'save.'.$type; $funcs = "image" . $type; $funcs($thump, $path);}
按固定宽高压缩
public function compressImgWH($src = '', $new_width='', $new_height=''){list($width, $height, $type, $attr) = getimagesize($src);$type = image_type_to_extension($type, false); $fun = "imagecreatefrom" . $type; $image = $fun($src); $thump = imagecreatetruecolor($new_width, $new_height); // 处理透明背景图片变成黑色的问题 if(strtolower($type)=='png'){ imageantialias($thump, true); $color = imagecolorallocate($thump, 255, 255, 255); imagecolortransparent($thump, $color); imagefill($thump, 0, 0, $color); } //将原图复制到其他图片上,并且按照一定宽高压缩 imagecopyresampled($thump, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); imagedestroy($image); // 1、浏览器直接输出 header('Content-Type: image/' . $type); $funcs = "image" . $type; $funcs($thump); // 2、保存到对应路径 $path = 'save.'.$type; $funcs = "image" . $type; $funcs($thump, $path);}
功能演示:
来源地址:https://blog.csdn.net/u012816216/article/details/129509302