动态GD图像宽度文本

时间:2009-11-15 16:55:07

标签: php fonts gd width

我正在尝试使用标题的自定义字体为我的网站增添趣味。对我来说,最合适的方法是使用PHP和GD。我编写了一个小脚本,它将根据$ _GET值输出动态文本,但有时候图像太宽,会移动其他所有内容。

如何根据文本的宽度调整图像的宽度?这是我到目前为止编写的代码:

<?php
// Settings
$sText = $_GET['t']; // Text of heading
$sFont = "font/AvantGarde-Book.ttf"; // Default font for headings
$sMain = $_GET['c'] ? $_GET['c'] : 0xF2AB27; // Get a font or default it

// Create the image
header("content-type: image/png"); // Set the content-type
$hImage = imagecreatetruecolor(200, 24);
ImageFill($hImage, 0, 0, IMG_COLOR_TRANSPARENT);
imagesavealpha($hImage, true);
imagealphablending($hImage, false);
imagettftext($hImage, 20, 0, 0, 24, $sMain, $sFont, $sText); // Draw the text
imagepng($hImage); // Generate the image
imagedestroy($hImage); // Destroy it from the cache ?>

谢谢!

2 个答案:

答案 0 :(得分:6)

好的,我明白了!对于可能遇到此问题的其他人,您需要添加:

// Calcuate the width of the image
$arSize = imagettfbbox(24, 0, $sFont, $sText);
$iWidth = abs($arSize[2] - $arSize[0]);
$iHeight = abs($arSize[7] - $arSize[1]);

在imagecreatetruecolor()

之前

答案 1 :(得分:4)

函数imagettfbbox将根据您选择的字体计算文本的大小。在调用imagecreatetruecolor时使用结果。