如何在不模糊图像的情况下在 gd 中创建透明背景?

How to create transparent background in gd without blurring image?

我正在尝试创建一个饼图,它将显示浏览器统计信息。

但是,当我尝试为图表创建透明背景时,文本比正常背景变得模糊。

    define('FONT', "C:/Windows/fonts/Arial.ttf");
    $data = ['edge' => 3, 'ie' => 4, 'firefox' => 12, 'chrome' => 40, 'opera' => 9, 'android' => 18];

    function textWidth($text, $fontSize) {
        $sizes = array_map(function($x){ return $x * .75; }, imagettfbbox($fontSize, 0, FONT, $text));
        return $sizes[6] - $sizes[4];
    }

    asort($data);

    $total = array_sum($data);
    $before = -90;

    $w = 300;
    $h = 300;

    $graph = imagecreatetruecolor($w * 2, $h * 2);

    // this is the part where background blurrs: remove this part to compare
    imagealphablending($graph, false);
    $transparency = imagecolorallocatealpha($graph, 0, 0, 0, 127);
    imagefill($graph, 0, 0, $transparency);
    imagesavealpha($graph, true);
    //part end

    $text_color = imagecolorallocate($graph, 0, 0, 0);

    foreach ($data as $key => $value) {     
        $ratio = 100 / $total * $value;
        $deg = $before + 3.6 * $ratio;

        $color = imagecolorallocate($graph, rand(128,255), rand(128,255), rand(128,255));
        imagefilledarc($graph, $w, $h, $w * 2, $h * 2, $before, $deg, $color, IMG_ARC_PIE);

        $posX = $w + $w * cos(deg2rad($deg - 1.8 * $ratio)) * .75;
        $posY = $w + $w * sin(deg2rad($deg - 1.8 * $ratio)) * .75;

        $ratio = floor($ratio);
        imagettftext($graph, 16, 0, $posX + textWidth($key, 18) / 2, $posY, $text_color, FONT, $key);
        imagettftext($graph, 16, 0, $posX + textWidth($ratio . "%", 18) / 2, $posY + 30, $text_color, FONT, $ratio . "%");

        $before = $deg;
    }

    header('Content-type: image/png');
    imagepng($graph);
    imagedestroy($graph);

我尝试在绘制图表的每个部分后创建透明背景,但没有成功。

如有任何帮助,我们将不胜感激。谢谢!

您可以删除以下行:

imagealphablending($graph, false);

或在设置透明度后重新启用 alpha 混合:

imagealphablending($graph, false);
$transparency = imagecolorallocatealpha($graph, 0, 0, 0, 127);
imagefill($graph, 0, 0, $transparency);
imagealphablending($graph, true); // add this
imagesavealpha($graph, true);

结果: