@Martin蓋斯勒的回答幾乎是正確的,但我無法讓我的文本完全適合圖像。我試過這個,完美的作品!
從PHP Manual's User Contributed Notes:
$text = "<?php echo \"hello, world\"; ?>";
$font = "./arial.ttf";
$size = "60";
$bbox = imagettfbbox($size, 0, $font, $text);
$width = abs($bbox[2] - $bbox[0]);
$height = abs($bbox[7] - $bbox[1]);
$image = imagecreatetruecolor($width, $height);
$bgcolor = imagecolorallocate($image, 255, 255, 255);
$color = imagecolorallocate($image, 0, 0, 0);
$x = $bbox[0] + ($width/2) - ($bbox[4]/2);
$y = $bbox[1] + ($height/2) - ($bbox[5]/2);
imagefilledrectangle($image, 0, 0, $width - 1, $height - 1, $bgcolor);
imagettftext($image, $size, 0, $x, $y, $color, $font, $text);
$last_pixel= imagecolorat($image, 0, 0);
for ($j = 0; $j < $height; $j++)
{
for ($i = 0; $i < $width; $i++)
{
if (isset($blank_left) && $i >= $blank_left)
{
break;
}
if (imagecolorat($image, $i, $j) !== $last_pixel)
{
if (!isset($blank_top))
{
$blank_top = $j;
}
$blank_left = $i;
break;
}
$last_pixel = imagecolorat($image, $i, $j);
}
}
$x -= $blank_left;
$y -= $blank_top;
imagefilledrectangle($image, 0, 0, $width - 1, $height - 1, $bgcolor);
imagettftext($image, $size, 0, $x, $y, $color, $font, $text);
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
我想使用TTF字體,我看了一些的imageftbbox頁面上的例子,但我似乎無法獲取文本的尺寸。 – usertest 2009-12-20 19:58:30
是的,我很抱歉,我起初回答了錯誤的問題 - 現在我已經爲TrueType字體提供了代碼。 – 2009-12-20 20:21:08
我試了一下代碼,發現錯誤「The image」test.php「無法顯示,因爲它包含錯誤。」 – usertest 2009-12-20 20:40:49