「人生若只如初见」

「人生若只如初见」

正在加载诗词...

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

  • kevin 2026年04月14日 4阅读 0评论
  • 先不管你的图片是多大,在处理的时候都以1000x1000的大小裁剪为圆形,然后再等比例缩放到300x300的大小,这样就得到了消除锯齿的圆形图片,前者越大,图片就越圆滑

    PHP代码

    <?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);
    }
    0
    打赏

    —— 评论区 ——

    请登录后发表评论
    立即登录 用户注册
    LOGIN