Chris Ensell
Chris Ensell

Reputation: 153

PHP GD imagecolorallocatealpha only makes grey text

Is there any reason why imagecolorallocatealpha() would only be making the text grey?

<?php
header('Content-Type: image/png');

function checkImg($imgname) {
    $im = @imagecreatefrompng($imgname);

if(!$im) {
    $im  = imagecreatetruecolor(150, 30);
    $bgc = imagecolorallocate($im, 255, 255, 255);
    $tc  = imagecolorallocate($im, 0, 0, 0);

    imagefilledrectangle($im, 0, 0, 150, 30, $bgc);

    imagestring($im, 1, 5, 5, 'Error loading ' . $imgname, $tc);
}

return $im;
}

$hr = 48;

$tOne = "VALID FOR";
$tTwo = $hr." HOURS";

$img = checkImg('img.png');

$font = 'helr67w.ttf';
$size = 9;

$red = imagecolorallocatealpha($img, 255, 0, 0, 75);

imagettftext($img, $size, 0, 225, 132, $red, $font, $tOne);
imagettftext($img, $size, 0, 225, 144, $red, $font, $tTwo);

imagepng($img);
imagedestroy($img);
?>

Upvotes: 0

Views: 1442

Answers (1)

hakre
hakre

Reputation: 197544

In your code you don't set the image to support an alpha channel. I can imagine that is causing the issue:

function checkImg($imgname) {
    $im = @imagecreatefrompng($imgname);

    if(!$im) {
        $im  = imagecreatetruecolor(150, 30);
        $bgc = imagecolorallocate($im, 255, 255, 255);
        $tc  = imagecolorallocate($im, 0, 0, 0);
        imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
        imagestring($im, 1, 5, 5, 'Error loading ' . $imgname, $tc);
    }

    // Turn off alpha blending and set alpha flag
    imagealphablending($im, true);
    imagesavealpha($im, true);
    return $im;
}

See imagesavealpha PHP Manual and imagealphablending PHP Manual

Upvotes: 1

Related Questions