Dynamic GD Image Width Text

I am trying to liven up my site using custom heading fonts. For me, the most appropriate way to do this is to use PHP and GD. I wrote a little script that will output dynamic text based on the value of $ _GET, however sometimes the image is too large, which moves everything else.

How can I get an image to adjust its width, depending on the width of the text? Here is the code that I have written so far:

<?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 ?> 

Thanks!

+4
source share
2 answers

Ok, I get it! For anyone who might have this problem, you need to add:

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

Before imagecreatetruecolor ()

+6
source

The imagettfbbox function will calculate the size of the text based on the font you select. Use the results in your appeal to imagecreatetruecoror.

+4
source

All Articles