PHPverse 2025

Voting

: seven plus one?
(Example: nine)

The Note You're Voting On

mike at mikeleigh dot com
18 years ago
I have been testing this function for a while now and have come up with many of the same issues that other people have touched upon. Not being able to calculate the width of the text correctly. Or if a solution is found then it won't work with a hanging letter or a negative start letter like 'j'.

Like Ralph I also wanted to draw a box around some text and this would require me being pixel perfect with the font. The trouble is I did not know which font would be used or which size. This led me to come up with a solution which I am sharing below.

<?php
function imagettfbboxextended($size, $angle, $fontfile, $text) {
/*this function extends imagettfbbox and includes within the returned array
the actual text width and height as well as the x and y coordinates the
text should be drawn from to render correctly. This currently only works
for an angle of zero and corrects the issue of hanging letters e.g. jpqg*/
$bbox = imagettfbbox($size, $angle, $fontfile, $text);

//calculate x baseline
if($bbox[0] >= -1) {
$bbox['x'] = abs($bbox[0] + 1) * -1;
} else {
//$bbox['x'] = 0;
$bbox['x'] = abs($bbox[0] + 2);
}

//calculate actual text width
$bbox['width'] = abs($bbox[2] - $bbox[0]);
if(
$bbox[0] < -1) {
$bbox['width'] = abs($bbox[2]) + abs($bbox[0]) - 1;
}

//calculate y baseline
$bbox['y'] = abs($bbox[5] + 1);

//calculate actual text height
$bbox['height'] = abs($bbox[7]) - abs($bbox[1]);
if(
$bbox[3] > 0) {
$bbox['height'] = abs($bbox[7] - $bbox[1]) - 1;
}

return
$bbox;
}
?>

The function above gives the correct x and y coordinates that the text should be drawn from and also gives the actual image width and height. This has been tested with various fonts and sizes ranging from 6 up to 144 points. Some of the output will appear to be incorrect and have an extra pixel on the right, using verdana at size 144 and outputting the character 'Q' for example. This is not an error as this is part of the anti-aliasing of the font output.

Example Usage:
<?php
$font
= 'c:\windows\fonts\verdana.ttf';
$font_size = 144;
$text = 'jÜyZgQ';
$bbox = imagettfbboxextended($font_size, 0, $font, $text);
?>

Return Values:
Array
(
[0] => -8
[1] => 40
[2] => 715
[3] => 40
[4] => 715
[5] => -177
[6] => -8
[7] => -177
[x] => 6
[width] => 722
[y] => 176
[height] => 216
)

Further notes can be found here along with images of the output of the function http://mikeleigh.com/links/imagettfbbox

<< Back to user notes page

To Top