Search code examples
phpgraphgd

How to create transparent background in gd without blurring image?


I'm trying to create a pie chart, which will display browser stats.

But, when I try to create a transparent background to chart, text goes blurry than normal background.

    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);

I've tried to create transparent background after drawing each parts of graph, but it didn't worked.

Any help would be appreciated. Thanks!


Solution

  • You can either remove the following line:

    imagealphablending($graph, false);
    

    Or re-enable alpha blending after setting the transparency:

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

    Result:

    non blurry image