Jump to content

Wrong Height For Image Using Imagettfbbox() With Script Font


Mike521

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.