c_shelswell Posted March 17, 2008 Share Posted March 17, 2008 Hi, I'm looking to make a selection of text headers for multiple sites using different fonts so I thought I'd try and use php to automate the process for me. Writing the text seems easy enough (imagettftext) but what i'm struggling with is how to set the size of the image to only be as big as is required by the length of the string i'm passing imagettftext. Is there anyway to do this? Cheers Quote Link to comment Share on other sites More sharing options...
c_shelswell Posted March 17, 2008 Author Share Posted March 17, 2008 Nobody have any ideas on this?? Cheers Quote Link to comment Share on other sites More sharing options...
craygo Posted March 17, 2008 Share Posted March 17, 2008 You could always just play around with certain sizes till you get a base. Lets say it take 15 pixels to create one letter with a space, you could get the length of the string and multiply it by the value. $text = "menu Item"; $length = strlen($text); $value = 15; $width = $length * $value; that way it will be dynamic. Ray Quote Link to comment Share on other sites More sharing options...
c_shelswell Posted March 17, 2008 Author Share Posted March 17, 2008 that's a really simple good idea. I was simply expecting it to be complicated so got lost!! Thanks very much Quote Link to comment Share on other sites More sharing options...
Barand Posted March 18, 2008 Share Posted March 18, 2008 If you are using the gd monospaced fonts <?php $text = 'Hello World'; $w = imagefontwidth(5) * strlen($text); $h = imagefontheight(5); $im = imagecreate ($w + 10, $h+10); $bg = imagecolorallocate($im, 200, 200, 200); $tcol = imagecolorallocate($im, 255, 0, 0); imagestring($im, 5, 5, 5, $text, $tcol); header("content-type: image/png"); imagepng ($im); imagedestroy($im); ?> If you use truetype font <?php $text = 'Hello World'; $bb = imagettfbbox(20, 0, 'c:/windows/fonts/arial.ttf', $text); $w = abs($bb[4] - $bb[0]); $h = abs($bb[5] - $bb[1]); $im = imagecreate ($w + 20, $h+20); $bg = imagecolorallocate($im, 200, 200, 200); $tcol = imagecolorallocate($im, 255, 0, 0); imagettftext($im, 20, 0, 10, $h+10, $tcol, 'c:/windows/fonts/arial.ttf', $text); header("content-type: image/png"); imagepng ($im); imagedestroy($im); ?> Quote Link to comment Share on other sites More sharing options...
c_shelswell Posted March 18, 2008 Author Share Posted March 18, 2008 exactly what i was looking for - thanks for your help Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.