PHP GD imagecolorallocatealpha只生成灰色文本

时间:2011-07-14 19:56:22

标签: php gd

是否有任何理由为什么imagecolorallocatealpha()只会使文字变灰?

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

1 个答案:

答案 0 :(得分:1)

在您的代码中,您不会将图像设置为支持Alpha通道。我可以想象这导致了这个问题:

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

请参阅imagesavealpha PHP Manualimagealphablending PHP Manual