2012-07-27 84 views
13

我簡單地試圖獲得用GD PHP生成的圖像的動態添加文本的寬度。但我有點不確定。我知道如何使用imageloadfont()加載字體,但是我可以使用.ttf文件嗎?我想知道使用12號字體的文本的寬度。當我嘗試使用我的ttf文件時,出現錯誤「Error reading font,invalid font header。」如果我需要一個.gdf文件,我可以在哪裏找到一個字體大小爲12的gdf文件?這是我的代碼:用PHP計算文本寬度GD

$newfont = imageloadfont("../fonts/arial.ttf"); 
$font_width = imagefontwidth($newfont); 
$font_height = imagefontheight($newfont); 
+2

乘坐看看[imagettfbbox](http://www.php.net/manual/en/function.imagettfbbox.php)和[imagettftext](http://php.net/manual/en/function.imagettftext.php)。 – Vatev 2012-07-27 23:39:36

回答

33

imageloadfont()用於加載用戶定義的位圖。如果你只是想使用Arial或任何其他TrueType字體(.ttf)或OpenType字體(.otf)(後者在GD lib中的支持是越野車),那麼你需要的是imagettftext()。在使用imagettftext()並將文字寫入圖片之前,您首先需要知道它是否適合。要知道這一點,你只需要調用imagettfbbox()並傳遞它的字體大小,文本的角度(0代表水平文本),.ttf或.otf字體文件的路徑以及文本本身的字符串,它將返回一個包含8個元素的數組,代表四個點作爲文本的邊界框(查看PHP手冊瞭解具體情況)。然後,您可以引用這些數組元素並執行計算,以便知道該特定字符串文本將佔用的寬度和高度。然後,您可以使用這些值創建一個具有特定寬度和高度的圖像,以便將文本全部顯示出來。

下面是一個簡單的腳本,完成你正在嘗試以獲得你做開始:

<?php # Script 1 

/* 
* This page creates a simple image. 
* The image makes use of a TrueType font. 
*/ 

// Establish image factors: 
$text = 'Sample text'; 
$font_size = 12; // Font size is in pixels. 
$font_file = 'Arial.ttf'; // This is the path to your font file. 

// Retrieve bounding box: 
$type_space = imagettfbbox($font_size, 0, $font_file, $text); 

// Determine image width and height, 10 pixels are added for 5 pixels padding: 
$image_width = abs($type_space[4] - $type_space[0]) + 10; 
$image_height = abs($type_space[5] - $type_space[1]) + 10; 

// Create image: 
$image = imagecreatetruecolor($image_width, $image_height); 

// Allocate text and background colors (RGB format): 
$text_color = imagecolorallocate($image, 255, 255, 255); 
$bg_color = imagecolorallocate($image, 0, 0, 0); 

// Fill image: 
imagefill($image, 0, 0, $bg_color); 

// Fix starting x and y coordinates for the text: 
$x = 5; // Padding of 5 pixels. 
$y = $image_height - 5; // So that the text is vertically centered. 

// Add TrueType text to image: 
imagettftext($image, $font_size, 0, $x, $y, $text_color, $font_file, $text); 

// Generate and send image to browser: 
header('Content-type: image/png'); 
imagepng($image); 

// Destroy image in memory to free-up resources: 
imagedestroy($image); 

?> 

更改值相應地滿足您的需求。不要忘記閱讀PHP手冊。

+2

很好的答案.. +1 – 2012-12-18 22:42:02

+0

對不起,但[**這東西不工作**](http://i.stack.imgur.com/54yoj.png)。這是它使用文字「666」(或任何其他數字AFAIK)和Courier New字體生成的內容。它並沒有真正與其他字體一起工作 - 總是在這裏和那裏削減一些東西。我明白,PHP背後的人無能爲力不是你的錯,但仍然是失望。 – 2016-04-29 04:51:05

+0

[另一個例子](http://i.stack.imgur.com/tYJV7.png)我突出了什麼是錯的。 – 2016-04-29 04:52:45

1

隨着GD2,在imagettfbbox的字體大小需要在PT的,而不是在像素與以下步驟轉換:

($ fontSizeInPixel * 3)/ 4