nbarone Posted June 30, 2009 Share Posted June 30, 2009 I am trying to create a title on the top of each dynamic page. The pages will be created and deleted regularly via a CMS, so it must stay dynamic. I am having an issue figuring out how to calculate image width based upon string length and font width. Basically, I can narrow it down to "close", but then when I use a string that's all CAPS, the string falls off of the image. I would also like the string to be centered in the image (best if the image was only ~5 pixels larger than the string on each side. Any input is appreciated. <?php $font = "coopheavy.ttf"; $title = $_REQUEST['title']; $imw = strlen($title) * 13; header ("Content-type: image/png"); $image = imagecreate($imw, 30); $bg = imagecolorallocate($image, 255, 255, 255); $fontColor = imagecolorallocate($image, 0, 0, 0); imagettftext($image, 24, 0,0, 24, $fontColor, $font, $title); imagepng($image); imagedestroy($image); ?> Link to comment https://forums.phpfreaks.com/topic/164251-solved-gd-dynamic-string-length-width/ Share on other sites More sharing options...
patrickmvi Posted June 30, 2009 Share Posted June 30, 2009 I would think that you'd have to extract size information from the font data/file itself to know how wide each character would be. Something else you could try to do is generate the text on a much larger contrasting canvas (like a green screen) and then detect where the text you've entered starts and ends and make the image the appropriate size. Link to comment https://forums.phpfreaks.com/topic/164251-solved-gd-dynamic-string-length-width/#findComment-866413 Share on other sites More sharing options...
rhodesa Posted June 30, 2009 Share Posted June 30, 2009 you can use http://us3.php.net/manual/en/function.imagettfbbox.php to calculate the height/width of the text that will be printed Link to comment https://forums.phpfreaks.com/topic/164251-solved-gd-dynamic-string-length-width/#findComment-866415 Share on other sites More sharing options...
nbarone Posted June 30, 2009 Author Share Posted June 30, 2009 you can use http://us3.php.net/manual/en/function.imagettfbbox.php to calculate the height/width of the text that will be printed This is exactly what I was looking for, thank you. Here is my new code, works great: <?php $font = "coopheavy.ttf"; $title = $_REQUEST['title']; $img_arr = imagettfbbox(24,0,$font,$title); $bot_right = $img_arr[2]; header ("Content-type: image/png"); $image = imagecreate($bot_right+20, 30); $bg = imagecolorallocate($image, 255, 255, 255); $fontColor = imagecolorallocate($image, 0, 0, 0); imagettftext($image, 24, 0, 10, 24, $fontColor, $font, $title); imagepng($image); imagedestroy($image); ?> Link to comment https://forums.phpfreaks.com/topic/164251-solved-gd-dynamic-string-length-width/#findComment-866424 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.