侧边栏壁纸

PHP将方形头像裁剪为圆形无锯齿的头像

2024年05月28日 455阅读 0评论 1点赞

思路:先不管你的图片是多大,在处理的时候都以1000x1000的大小裁剪为圆形,然后再等比例缩放到300x300的大小,这样就得到了消除锯齿的圆形图片,前者越大,图片就越圆滑~

对比图

演示图

废话不多说直接上代码
<?php
// 示例:输出圆形图片
header('Content-Type: image/png');
echo getimg("https://q.qlogo.cn/headimg_dl?dst_uin=778713968&spec=640", 300);


// 制作圆形图片
function getimg($imageUrl, $size)
{
    // 创建画布
    $canvasSize = 1000; // 处理时的图片尺寸
    $canvas = imagecreatetruecolor($canvasSize, $canvasSize);
    // 设置透明背景
    imagealphablending($canvas, false);
    imagesavealpha($canvas, true);
    $transparentColor = imagecolorallocatealpha($canvas, 0, 0, 0, 127);
    imagefilledrectangle($canvas, 0, 0, $canvasSize, $canvasSize, $transparentColor);
    // 加载原始图片
    $sourceImage = imagecreatefromjpeg($imageUrl);
    $sourceWidth = imagesx($sourceImage);
    $sourceHeight = imagesy($sourceImage);
    // 放大图片
    $enlargedWidth = $sourceWidth * 1.5;
    $enlargedHeight = $sourceHeight * 1.5;
    $enlargedImage = imagecreatetruecolor($enlargedWidth, $enlargedHeight);
    imagecopyresampled($enlargedImage, $sourceImage, 0, 0, 0, 0, $enlargedWidth, $enlargedHeight, $sourceWidth, $sourceHeight);
    // 计算裁剪为圆形的半径
    $radius = $canvasSize / 2;
    // 裁剪为圆形
    for ($x = 0; $x < $canvasSize; $x++) {
        for ($y = 0; $y < $canvasSize; $y++) {
            $dx = $x - $radius;
            $dy = $y - $radius;
            $distance = sqrt($dx * $dx + $dy * $dy);
            if ($distance < $radius) {
                // 在圆内部
                imagesetpixel($canvas, $x, $y, imagecolorat($enlargedImage, $enlargedWidth / $canvasSize * $x, $enlargedHeight / $canvasSize * $y));
            }
        }
    }
    // 输出的图片尺寸
    $end = imagecreatetruecolor($size, $size);
    imagesavealpha($end, true);
    $transparency = imagecolorallocatealpha($end, 0, 0, 0, 127);
    imagefill($end, 0, 0, $transparency);
    imagealphablending($end, false);
    imagesavealpha($end, true);
    imagecopyresampled($end, $canvas, 0, 0, 0, 0, $size, $size, $canvasSize, $canvasSize);
    imagepng($end);
    // 释放资源
    imagedestroy($canvas);
    imagedestroy($sourceImage);
    imagedestroy($enlargedImage);
    imagedestroy($end);
}
1
打赏

—— 评论区 ——

昵称
邮箱
网址
取消
舔狗日记