2012-10-01 168 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);