PHP程序开发过程中经常会碰到这样的问题,根据网页前台要求对原图片进行处理,生成符合网页前端尺寸要求的缩略图,同时,还要满足居中展示和PNG背景透明的要求。
举个例子,有一张800*600的图片,网页前端缩略图尺寸是200*200,PHP需要对这个图片进行以下处理。
1、压缩尺寸,将图片等比压缩到200*150,注意,这里的尺寸并不是200*200,因为原图并不是正方形的图片,宽度只有600;
2、新建一个画布,背景色为白色,根据图片格式,如果是PNG或GIF图片,设置背景完全透明;
3、将之前压缩成200*150的图片放入画布中,注意x轴需要偏移(200-150)/2=25px,这样才能在画布中居中。
流程已经清楚了,接下一就是代码编写了,以下是相应的函数代码,转载请注明出处:江西居道科技有限公司 www.juguw.net
/** * 生成裁剪图函数(支持图片格式:gif、jpeg、png和bmp) * @param string $src 源图片路径 * @param int $width 缩略图宽度(只指定高度时进行等比缩放) * @param int $width 缩略图高度(只指定宽度时进行等比缩放) * @param string $filename 保存路径(不指定时直接输出到浏览器) * @return bool */ function cutThumb($src, $width = null, $height = null, $filename = null) { if (!isset($width) && !isset($height)) return false; if (isset($width) && $width < 0) return false; if (isset($height) && $height < 0) return false; if(empty($width) && empty($height)) return false; $size = getimagesize($src); if (!$size) return false; list($src_w, $src_h, $src_type) = $size; $src_mime = $size['mime']; switch($src_type) { case 1 : $img_type = 'gif'; break; case 2 : $img_type = 'jpeg'; break; case 3 : $img_type = 'png'; break; case 15 : $img_type = 'wbmp'; break; default : return false; } if(empty($width)) $width=$height; if(empty($height)) $height=$width; $rate_h = $height/$src_h; $rate_w = $width/$src_w; //缩放比例 //以大的比例进行缩放 $rate = $rate_h<$rate_w?$rate_w:$rate_h; //获取缩放后的图片大小,及裁剪的左上角位置 if($rate<1){ $w = $src_w*$rate; $h = $src_h*$rate; $x = ($w-$width)/2; $y = ($h-$height)/2; }else{ //不需要进行缩放 $w = $src_w; $h = $src_h; $x=0;$y=0; //超出的一边进行裁剪 if($w>$width){ $x = ($w-$width)/2; } if($h>$height){ $y = ($h-$height)/2; } } $imagecreatefunc = 'imagecreatefrom' . $img_type; $src_img = $imagecreatefunc($src); imagesavealpha($src_img,true); //先进行缩放 $resize_img = imagecreatetruecolor($w, $h); imagealphablending($resize_img,false);//这里很重要,意思是不合并颜色,直接用$img图像颜色替换,包括透明色; imagesavealpha($resize_img,true);//这里很重要,意思是不要丢了$thumb图像的透明色; imagecopyresampled($resize_img, $src_img,0, 0, 0, 0, $w, $h, $src_w, $src_h); //完成缩放,再进行裁剪 $dest_img = imagecreatetruecolor($width, $height); imagealphablending($dest_img,false);//这里很重要,意思是不合并颜色,直接用$img图像颜色替换,包括透明色; imagesavealpha($dest_img,true);//这里很重要,意思是不要丢了图像的透明色; if ($img_type!='png' && $img_type!='gif'){ $bg = imagecolorallocate($dest_img,255,255,255); //设置背景色为白色, }else{ $bg = imagecolorallocatealpha($dest_img,255,255,255,127); //设置背景色为白色,127表示背景完全透明 } imagecolortransparent($dest_img,$bg); //设置透明 imagefill($dest_img,0,0,$bg); imagecopyresampled($dest_img, $resize_img, ($width-$w)/2, ($height-$h)/2,0, 0,$w, $h, $w, $h); //这里不需要再进行缩放,直接裁剪就可以,所以后面4个参数两两相同 $imagefunc = 'image' . $img_type; if ($filename) { $imagefunc($dest_img, $filename,$img_type=='png'?CONST_IMGQUALITY/10:CONST_IMGQUALITY); //PNG格式的图片质量值介于0-9之间 } else { header('Content-Type: ' . $src_mime); $imagefunc($dest_img); } imagedestroy($src_img); imagedestroy($resize_img); imagedestroy($dest_img); return true; }
PHP生成指定大小的背景透明且尺寸固定居中显示的缩略图 下载