Reputation: 984
I need to create an image through php with a variable text inside. The images has fixed width and variable height since some times I have a really short text, other times a really long text inside it.
When I create the image, imagecreate function wants exact dimensions and this is an issue since my text is variable. Is there a quick way to sort it out?
Thanks
Upvotes: 0
Views: 1225
Reputation: 984
Here it is the code:
<?
header("Content-Type: image/png");
if(!isset($_GET['size'])) $_GET['size'] = 44;
if(!isset($_GET['text'])) $_GET['text'] = "Hello, world!";
$font_type="./fonts/Arial.ttf";
//word wrap
$_GET['text'] = wordwrap($_GET['text'], 30, "\n");
$size = imagettfbbox($_GET['size'], 0, $font_type, $_GET['text']);
$xsize = abs($size[0]) + abs($size[2])+20;
$ysize = abs($size[5]) + abs($size[1])+20;
$image = imagecreate($xsize, $ysize);
$blue = imagecolorallocate($image, 0, 0, 255);
$white = imagecolorallocate($image, 255,255,255);
imagettftext($image, $_GET['size'], 0, abs($size[0])+5, abs($size[5])+5, $white, $font_type, $_GET['text']);
imagepng($image);
imagedestroy($image);
?>
Upvotes: 1
Reputation: 24645
Use the imagettfbbox to get at the height and width of the text prior to creating the image.
Upvotes: 2