Mike521 Posted October 9, 2012 Share Posted October 9, 2012 I'm generating a PNG image (transparent background) of some text on the fly. The text will be whatever the user typed, using English 111 Vivace BT (a script) as the font. The image will always be 100px tall by 200px wide, regardless of how large the text is. I want the text to be horizontally centered and positioned as close to the top of the image as possible. This all works generally fine except that imagettfbbox() appears to be returning incorrect points for the bounding box, it thinks the text is taller than it really is, and therefore some blank space is appearing at the top of the image, before the text. Please see the attached example png, I drew some red guidelines to demonstrate the problem. The left side shows a guideline that is 38px tall, which is what imagettfbbox() thinks is the height of the text. The right side shows a line measured against the text itself, and it's only 26px tall. is there a more accurate way to get the box? Quote Link to comment https://forums.phpfreaks.com/topic/269263-wrong-height-for-image-using-imagettfbbox-with-script-font/ Share on other sites More sharing options...
Barand Posted October 9, 2012 Share Posted October 9, 2012 The 38px will include the line spacing (leading) that the font designer decided was most suitable for printing multiple line of that font. Quote Link to comment https://forums.phpfreaks.com/topic/269263-wrong-height-for-image-using-imagettfbbox-with-script-font/#findComment-1384084 Share on other sites More sharing options...
DarkerAngel Posted October 10, 2012 Share Posted October 10, 2012 I had used this one in one of my codes it gives a better representation of the text bounding box, it is taken from php.net, though it looks like it has been rewritten a couple times. function better_imagettfbbox($size, $angle, $font, $text) { $dummy = imagecreate(1, 1); $black = imagecolorallocate($dummy, 0, 0, 0); $bbox = imagettftext($dummy, $size, $angle, 0, 0, $black, $font, $text); imagedestroy($dummy); return $bbox; } It works better because it actually draws the element rather than assuming the dimensions, but functions the same way. You can try it, hope it helps. Quote Link to comment https://forums.phpfreaks.com/topic/269263-wrong-height-for-image-using-imagettfbbox-with-script-font/#findComment-1384097 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.