imagettfbox inaccurate

I’m having issues with text lining up where it should. Every tutorial I can find tells me to use imagettfbox to find the dimensions of the text. I do this, but the text doesn’t fit within those dimensions.

See the example below:
[php] <?php
// Create image and colours
$im = imagecreatetruecolor(200, 100);
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
$red = imagecolorallocate($im, 255, 0, 0);

//Set the background to be white
imagefilledrectangle($im, 0, 0, 200, 100, $white);

//font file
$font = “ARIAL.TTF”;

//set sample text and fontsize
$text=“102”;
$size = 25;

//calculate height and width of text1
$bbox = imagettfbbox($size, 0, $font, $text);
$width = $bbox[2] - $bbox[0];
$height = $bbox[5] - $bbox[3];

//draw rectangle that should house the text
imagefilledrectangle($im, 50, 40, 50+$width, 40+$height, $red);
//draw text at same startpoint as rectangle
imagettftext($im, $size, 0, 50, 40, $black, $font, $text);

// Output to browser
header(‘Content-type: image/png’);

imagepng($im);
imagedestroy($im);
?> [/php]
This should output a red rectangle, containing the text. It doesn’t - the text is slightly to the right of where it should be. This only happens with some strings - ones that contain a “1” tend not to work, while some others work perfectly. Here is the output for 2 strings:

The top (red) one works as it should, the string is entirely within the bounding box, but the bottom (green) one doesn’t - it’s offset to the right.

Does anyone know what is happening, and what I need to do to make the text fit correctly within the bounding box? I’ve tested this with multiple fonts, including monospace fonts - the same thing always happens.

Sponsor our Newsletter | Privacy Policy | Terms of Service