最近在写API,用到了GD画图,裁剪圆形图片后发现有明显的锯齿感,然后将裁剪的图片比例由300x300改为1000x1000后发现锯齿感有所缓解,于是按照这个思路:先不管你的图片是多大,在处理的时候都以1000x1000的大小裁剪为圆形,然后再等比例缩放到300x300的大小,这样就得到了消除锯齿的圆形图片,前者越大,图片就越圆滑~

对比图

废话不多说直接上代码

<?php
// 示例:输出圆形图片
header('Content-Type: image/png');
echo getimg("https://q.qlogo.cn/headimg_dl?dst_uin=1872786834&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);
}
最后修改:2023 年 08 月 19 日
如果觉得我的文章对你有用,请随意赞赏