PHP imagettftext在透明背景上创建黑色边缘

时间:2012-10-01 12:05:45

标签: php imagettftext

我有这段代码:

$im = imagecreatetruecolor(70, 25);

$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);

imagecolortransparent($im, imagecolorallocate($im, 0,0,0));

$font = 'font.ttf';

imagettftext($im, 20, 0, 3, 22, $white, $font, $randomnr);

header("Expires: Wed, 1 Jan 1997 00:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

header ("Content-type: image/png");
imagepng($im);
imagedestroy($im);

就像我在标题中说的那样,它会在文本周围创建一些黑色边缘。 我也尝试使用imagealphablending / imagesavealpha并且我得到了相同的结果(我在透明背景上使用了白色文字,以便您可以看到我在说什么):

black edges

更新:解决方案是:

$im = imagecreatetruecolor(70, 25);
$font = 'font.ttf';
//antialiasing:
$almostblack = imagecolorallocate($im,254,254,254); 
imagefill($im,0,0,$almostblack);
$black = imagecolorallocate($im,0,0,0); 
imagecolortransparent($im,$almostblack);

imagettftext($im, 20, 0, 3, 22, $white, $font, $randomnr);
...

2 个答案:

答案 0 :(得分:6)

这样的事情应该做的工作:

$width = 70;
$height = 25;

$im = imagecreatetruecolor($width, $height);

$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 221, 221, 221);

imageSaveAlpha($im, true);
imageAlphaBlending($im, false);

$transparent = imageColorAllocateAlpha($im, 0, 0, 0, 127);
imagefilledrectangle($im, 0, 0, $width-1, $height-1, $transparent);
imageAlphaBlending($im, true);

$font = 'font.ttf';
$randomnr = "1234";
imagettftext($im, 20, 0, 3, 22, $white, $font, $randomnr);

header("Expires: Wed, 1 Jan 1997 00:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

header ("Content-type: image/png");
imagepng($im);
imagedestroy($im);

答案 1 :(得分:2)

这就是你在这里指定的内容:

imagecolortransparent($im, imagecolorallocate($im, 0,0,0));

如果您想使用其他颜色进行透明,请选择其他颜色。现在你正在使用黑色。

请参阅imagecolortransparentDocs

另请注意该用户在同一页面上的说明:

  

由于抗锯齿功能,带有文字的透明背景似乎无法正常工作。