tp5/tp6 think-image 添加图片导圆角功能
类文件:vendor/topthink/think-image/src/Image.php
/**
* 处理圆角图片
* @param integer $radius 圆角半径(默认15,0表示圆形)
* @return $this
*/
public function radius($radius = 15)
{
$w = $this->width();
$h = $this->height();
$radius = $radius == 0 ? min($w, $h) / 2 : $radius;
// 创建透明画布
$img = imagecreatetruecolor($w, $h);
imagesavealpha($img, true);
$bg = imagecolorallocatealpha($img, 255, 255, 255, 127);
imagefill($img, 0, 0, $bg);
// 绘制圆角遮罩
for ($x = 0; $x < $w; $x++) {
for ($y = 0; $y < $h; $y++) {
$color = imagecolorat($this->im, $x, $y);
if (($x >= $radius && $x <= ($w - $radius)) || ($y >= $radius && $y <= ($h - $radius))) {
imagesetpixel($img, $x, $y, $color);
} else {
// 四角区域判断
$points = [
[$radius, $radius], // 左上
[$w - $radius, $radius], // 右上
[$radius, $h - $radius], // 左下
[$w - $radius, $h - $radius] // 右下
];
foreach ($points as $point) {
$dx = $x - $point[0];
$dy = $y - $point[1];
if ($dx * $dx + $dy * $dy <= $radius * $radius) {
imagesetpixel($img, $x, $y, $color);
break;
}
}
}
}
}
$this->im = $img;
return $this;
}应用
\think\Image::open('input.jpg')->radius(20)->save('output.png');