Jump to content

Recommended Posts

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?

 

post-11556-0-74852500-1349804125_thumb.png

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.