以下是用 PHP 实现图片圆角处理的函数:
function imgRadius($src_img, $radius) {
// 获取图片信息
$size = getimagesize($src_img);
$width = $size[0];
$height = $size[1];
// 建立图像
$src_img_res = imagecreatefromstring(file_get_contents($src_img));
$dest_img_res = imagecreatetruecolor($width, $height);
// 分配背景色
$bg_color = imagecolorallocate($dest_img_res, 255, 255, 255);
imagefill($dest_img_res, 0, 0, $bg_color);
// 生成掩模
$mask_img_res = imagecreatetruecolor($width, $height);
$mask_bg_color = imagecolorallocate($mask_img_res, 0, 0, 0);
imagefill($mask_img_res, 0, 0, $mask_bg_color);
$mask_radius = min($width, $height) / 2 - $radius;
imagefilledellipse($mask_img_res, $width / 2, $height / 2, $mask_radius * 2, $mask_radius * 2, imagecolorallocate($mask_img_res, 255, 255, 255));
// 透明化图像
imagesavealpha($dest_img_res, true);
$trans_color = imagecolorallocatealpha($dest_img_res, 0, 0, 0, 127);
imagefill($dest_img_res, 0, 0, $trans_color);
// 合并图像和掩模
imagecopymerge($dest_img_res, $src_img_res, 0, 0, 0, 0, $width, $height, 100);
imagecopymerge($dest_img_res, $mask_img_res, 0, 0, 0, 0, $width, $height, 50);
// 输出图像
header('Content-type: image/png');
imagepng($dest_img_res);
// 释放资源
imagedestroy($src_img_res);
imagedestroy($dest_img_res);
imagedestroy($mask_img_res);
}
使用方法:
// 加载图片,并设置圆角大小为 30
imgRadius('example.jpg', 30);
该函数将输出圆角处理后的 PNG 图片。