2010-08-15 108 views
0

我目前正在一個網站上工作,最近一直在使用GD與PHP自動創建透明圖像,這些透明圖像由網站上用於導航,標題等的文本組成。它爲我節省了大量的時間在Photoshop中,我可以在需要時立即更改按鈕上的文字。PHP GD從創建的PNG中修剪透明像素

好吧,我已經在這裏遇到了死衚衕。我找到了將「文本框」大小設置爲我的圖像的方法,以確定文本的大小。但我面臨的問題是,我使用的TTF字體與GD期望的大小不同。基本上,最後一個字母將被切掉輸出的圖像。所以我想知道是否有辦法解決這個問題,同時保持文本的緊密邊緣,或使原始文本框的尺寸更大,然後「修剪」圖像上的透明像素。

這是我與現在使用的代碼...

<? 
$text = strip_tags($_GET['btn']); 
if(file_exists('nav_'.$text.'.png')) { 
    header("Content-type: image/png"); 

    $image = imagecreatefrompng('nav_'.$text.'.png'); 
    imagesavealpha($image, true); 
    imagealphablending($image, false); 
    imagepng($image); 
    imagedestroy($image); 
} else { 
    header("Content-type: image/png"); 

    $fontSize = 10; 
    $angle = 0; 
    $font = "RonniaBold.ttf"; 

    $size = imagettfbbox($fontSize, $angle, $font, $text); 
    $image = imagecreatetruecolor(abs($size[2]) + abs($size[0]) + 5, abs($size[7]) + abs($size[1]) + 5); 
    imagesavealpha($image, true); 
    imagealphablending($image, false); 

    $transparentColor = imagecolorallocatealpha($image, 200, 200, 200, 127); 
    imagefill($image, 0, 0, $transparentColor); 

    $textColor = imagecolorallocate($image, 125, 184, 222); 
    imagettftext($image, $fontSize, 0, 1, abs($size[5])+1, $textColor, $font, str_replace('_',' ',strtoupper($text))); 
    imagepng($image, 'nav_'.$text.'.png', 0); 
    imagedestroy($image); 
} 
?> 

希望你們有一些有識之士到這一點,我真的可以用它!

回答

2

只要有可能,我使用Imagick class,因爲我更喜歡ImageMagick庫。下面的例子幾乎是逐字從here給出的例子。它創建基於所提供的文本尺寸的圖像:

$text = 'Hello World!'; 

// Create a new ImageMagick objects. 
$im = new Imagick(); 
$draw = new ImagickDraw(); 
$colour = new ImagickPixel('#000000'); 
$background = new ImagickPixel('none'); 

// Set font properties. 
$draw->setFont('Fertigo_PRO.otf'); 
$draw->setFontSize(72); 
$draw->setFillColor($colour); 
$draw->setStrokeAntialias(true); 
$draw->setTextAntialias(true); 

// Get font metrics. 
$fm = $im->queryFontMetrics($draw, $text); 

// Create text. 
$draw->annotation(0, $fm['ascender'], $text); 

// Create a new empty canvas, using the text size. 
$im->newImage($fm['textWidth'], $fm['textHeight'], $background); 

// Create the image. 
$im->setImageFormat('png'); 
$im->drawImage($draw); 

// Save the image. 
$im->writeImage('test.png'); 

如果你想在Imagick類的詳細信息,我建議從Mikko's Blog優秀Imagick articles

$size = imagettfbbox($fontSize, $angle, $font, $text); 

但是,當你寫:要求與imagettfbox文本框的大小,當您使用$文本 -

+0

我認爲Imagick對做不同的事情要好得多,但問題是我的主機沒有安裝在他們的服務器上,並且由於與另一個插件的衝突而無法安裝。這就是爲什麼我試圖用GD做到這一點。 – 2010-08-16 02:10:13

2

你必須與你的代碼一個問題,阻止您確定您的文本的正確大小將文本添加到使用strtoupper($ text)的圖像 - 這會使文字更大(除非使用等寬字體)。