1. 程式人生 > >php給圖片添加圓角並且保持透明,可做圓形頭像

php給圖片添加圓角並且保持透明,可做圓形頭像

ger ++ href bsp esc ring 顏色 com 公式

原文鏈接:https://www.zhaokeli.com/article/8031.html

給圖片添加圓角,

用到的主要的(判斷一個點是否在圓內)的公式在上面所說的生成圓形圖片文章中。

然後掃描原圖把每個個適合的像素畫到一個透明的圖片上去

根據想添加的圓角大小來生成一定的圓角

如圖

技術分享圖片

首先根據圓角確定圖片四角的正方形形狀,掃描的時候只要是不在這些範圍內的像素才畫上去

<?php
if (($x >= $radius && $x <= ($w - $radius)) || ($y >= $radius && $y <= ($h - $radius
))) { //不在四角的範圍內,直接畫 imagesetpixel($img, $x, $y, $rgbColor); } ?>

經過上面過濾之後就只剩下四個角的位置沒有像素啦,如圖

技術分享圖片

然後四個角的圓心半徑都知道就可以判斷當前像素點是不是在圓內如果在圓內就畫這個像素

<?php
/**
 * blog:http://www.zhaokeli.com
 * 處理圓角圖片
 * @param  string  $imgpath 源圖片路徑
 * @param  integer $radius  圓角半徑長度默認為15,處理成圓型
 * @return [type]           [description]
 
*/ function radius_img($imgpath = ‘./t.png‘, $radius = 15) { $ext = pathinfo($imgpath); $src_img = null; switch ($ext[‘extension‘]) { case ‘jpg‘: $src_img = imagecreatefromjpeg($imgpath); break; case ‘png‘: $src_img = imagecreatefrompng($imgpath);
break; } $wh = getimagesize($imgpath); $w = $wh[0]; $h = $wh[1]; // $radius = $radius == 0 ? (min($w, $h) / 2) : $radius; $img = imagecreatetruecolor($w, $h); //這一句一定要有 imagesavealpha($img, true); //拾取一個完全透明的顏色,最後一個參數127為全透明 $bg = imagecolorallocatealpha($img, 255, 255, 255, 127); imagefill($img, 0, 0, $bg); $r = $radius; //圓 角半徑 for ($x = 0; $x < $w; $x++) { for ($y = 0; $y < $h; $y++) { $rgbColor = imagecolorat($src_img, $x, $y); if (($x >= $radius && $x <= ($w - $radius)) || ($y >= $radius && $y <= ($h - $radius))) { //不在四角的範圍內,直接畫 imagesetpixel($img, $x, $y, $rgbColor); } else { //在四角的範圍內選擇畫 //上左 $y_x = $r; //圓心X坐標 $y_y = $r; //圓心Y坐標 if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) { imagesetpixel($img, $x, $y, $rgbColor); } //上右 $y_x = $w - $r; //圓心X坐標 $y_y = $r; //圓心Y坐標 if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) { imagesetpixel($img, $x, $y, $rgbColor); } //下左 $y_x = $r; //圓心X坐標 $y_y = $h - $r; //圓心Y坐標 if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) { imagesetpixel($img, $x, $y, $rgbColor); } //下右 $y_x = $w - $r; //圓心X坐標 $y_y = $h - $r; //圓心Y坐標 if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) { imagesetpixel($img, $x, $y, $rgbColor); } } } } return $img; } header("content-type:image/png"); $imgg = radius_img(‘./tt.png‘, 20); imagepng($imgg); imagedestroy($imgg); ?>

原圖:

技術分享圖片

處理過後

技術分享圖片

如果圖片是正方形,圓角半徑直接傳圖形寬的一半就可以處理成圓形

如:

技術分享圖片

<?php
header("content-type:image/png");
$imgg = radius_img(‘./tx.png‘, 147);
imagepng($imgg);
imagedestroy($imgg);
?>

處理後:

技術分享圖片

php給圖片添加圓角並且保持透明,可做圓形頭像