版权声明:CopyRight @CSDN 码农Robin https://blog.csdn.net/weixin_41423450/article/details/84646408
在项目开发过程中少不了会用到图片上传功能,考虑到服务器带宽及磁盘空间,需要对图片进行压缩。
前端的压缩可以节约带宽,后端的压缩可以节省磁盘空间。
function resizeImage($source,$percent=0.5){
if(empty($source)){
return false;
}
//获取原图宽高,图片类型
list($width, $height, $type) = getimagesize($source);
$type = image_type_to_extension($type,false);
$new_width = $width * $percent;
$new_height = $height * $percent;
//等比例创建画布
$image_thump = imagecreatetruecolor($new_width,$new_height);
$bg = imagecolorallocate($image_thump,255,255,255);
imagefill($image_thump,0,0,$bg);
$fun = "imagecreatefrom".$type;
$img = $fun($source);
ImageDestroy($source);
//将原图复制到图片载体上面,并且按照一定比例压缩,极大的保持了清晰度
imagecopyresampled($image_thump,$img,0,0,0,0,$new_width,$new_height,$width,$height);
$func = "image".$type;
$func($image_thump,$source);
//销毁内存
ImageDestroy($image_thump);
return true;
}
另:小程序的图片上传接口自带压缩图片功能,在配置项中有,接口地址