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手冊。
乘坐看看[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