The PHP code below generates text as a dynamically created image, how would I be able to get the image to only be as large as the text? Thanks.
<?php
header('Content-Type: image/jpeg');
$text='Test';
$img = imageCreate(200,200);
imagecolorallocate($img, 255, 255, 255);
$textColor = imagecolorallocate($img, 0, 0, 0);
imagefttext($img, 15, 0, 0, 55, $textColor, 'bgtbt.ttf', $text);
imagejpeg($img);
imagedestroy($img);
?>
UPDATE 1: I found the answer here with the example of the original poster – Creating IMage from Text in PHP – how can I make multiline?
UPDATE 2: Martin Geisler’s version also works well
When using a TrueType font, you use the
imageftbboxfunction to obtain the bounding box for a string typeset with your font. The bounding box gives the offsets from the base-point to the four corners in the rectangle occupied by the text. So if you store the bounding box in$bband useimagefttextto put text at($x, $y), then the corners will have these coordinates:That tells us that we want an image width of
($x + $bb[2]) - ($x + $bb[6]) = $bb[2] - $bb[6]and similarly an image height of$bb[3] - $bb[7]. The text should then be rendered at coordinates(-$bb[6], -$bb[7])inside that picture since we want to haveYou can try it out with this code. Put it into a file called
img.phpand browse toimg.php?q=Helloto test:If you use the bitmap fonts instead, then look at the
imagefontwidthandimagefontheightfunctions.