2012-10-01 170 views
4

产生黑边我有这样的代码: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

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

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

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

请参阅imagecolortransparentDocs

也采取同一页上记下此用户的注意事项:

透明背景的文字似乎并没有因为抗锯齿的工作得很好。

+0

是的,我认为这开启抗锯齿的问题......是一个疗法的方式来解决这个问题?我想黑色是透明的。正如我在图像中说的是一个透明的bg,上面有白色文字,所以图像应该是完全白色的。 – Sp3ct3R

+0

您可以尝试先用透明色填充图像。另外,当你创建输出图像时,确保它有一个8位的alpha通道。 – hakre

+0

如何用8位alpha输出? – Sp3ct3R

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