100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > PHP 裁剪图片成圆形

PHP 裁剪图片成圆形

时间:2020-04-25 14:32:58

相关推荐

PHP 裁剪图片成圆形

php裁剪当前图片为圆形。

注意事项:

当前裁剪是将图片裁剪为圆形,既把利用把图片非圆形背景换为透明实现的,因此被处理的图片最好是正方形,不然程序不知道图片的那部分是要保留的,令最好的呈现结果不尽如人意。当前利用php自带的函数,实现原理是在透明画布上描点的方式,既创建一个和原图片相同的画布,然后使用循环的方式在原图上进行取色,得到相应坐标的色彩之后,绘制到对应的透明画布上,内存开销会随着像素点的增加而增加。

所以为了防止程序内存崩溃,最好是先将图片进行压缩之后,比如压缩为100 x 100, 80 x 80的正方形图片之后,再进行裁剪。

<?php/*** 图片圆角处理函数** @param source $srcFile 本地图片路径* @param integer $radius 圆角大小 = 最短边的长度 / $radius*/function roundImgs($srcFile, $radius=2) {//得到图片后缀$ext= pathinfo($srcFile);//设定圆形图片名称为“当前图片名称_cir”,并组装成本地圆形图片路径$img_path = $ext['dirname']."/".$ext['filename']."_cir.".$ext['extension'];//检测圆形图片存在的时候直接当前图片返回if(is_file($img_path)) return $img_path;$data = getimagesize($srcFile);switch ($data['2']) {case 1:$im = imagecreatefromgif($srcFile);break;case 2:$im = imagecreatefromjpeg($srcFile);break;case 3:$im = imagecreatefrompng($srcFile);break;case 6:$im = imagecreatefromwbmp($srcFile);break;}$srcImg = $im;$w = imagesx($srcImg);$h = imagesy($srcImg);$radius = min($w, $h) / $radius;$img = imagecreatetruecolor($w, $h);imagesavealpha($img, true); // 设置透明通道$bg = imagecolorallocatealpha($img, 255, 255, 255, 127); // 拾取一个完全透明的颜色, 最后一个参数127为全透明imagefill($img, 0, 0, $bg);$r = $radius; // 圆 角半径for ($x = 0; $x < $w; $x++) {for ($y = 0; $y < $h; $y++) {$rgbColor = imagecolorat($srcImg, $x, $y);if (($x >= $radius && $x <= ($w - $radius)) || ($y >= $radius && $y <= ($h - $radius))) {imagesetpixel($img, $x, $y, $rgbColor); // 不在四角的范围内,直接画} else {// 在四角的范围内选择画// 上左$yx = $r; // 圆心X坐标$yy = $r; // 圆心Y坐标if (((($x - $yx) * ($x - $yx) + ($y - $yy) * ($y - $yy)) <= ($r * $r))) {imagesetpixel($img, $x, $y, $rgbColor);}// 上右$yx = $w - $r; // 圆心X坐标$yy = $r; // 圆心Y坐标if (((($x - $yx) * ($x - $yx) + ($y - $yy) * ($y - $yy)) <= ($r * $r))) {imagesetpixel($img, $x, $y, $rgbColor);}// 下左$yx = $r; // 圆心X坐标$yy = $h - $r; // 圆心Y坐标if (((($x - $yx) * ($x - $yx) + ($y - $yy) * ($y - $yy)) <= ($r * $r))) {imagesetpixel($img, $x, $y, $rgbColor);}// 下右$yx = $w - $r; // 圆心X坐标$yy = $h - $r; // 圆心Y坐标if (((($x - $yx) * ($x - $yx) + ($y - $yy) * ($y - $yy)) <= ($r * $r))) {imagesetpixel($img, $x, $y, $rgbColor);}}}}switch ($data['2']) {case 1:imagegif($img,$img_path);break;case 2:imagejpeg($img,$img_path);break;case 3:imagepng($img,$img_path);break;case 6:image2wbmp($img,$img_path);break;}imagedestroy($img);return $img_path;}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。