PHP imagettfbbox and imagettftext give a different width for the same character

368 Views Asked by At

I would like to know the width of a letter before I write it to an image. I am using imagettfbbox for this. However the width I get from this function does not seem to be the same as the width I get after drawing the letter. The font I am using to draw is FreeSans Medium Style

The code I wrote to test this is as following:

/* Create the temp image. */
$tempImage = imagecreatetruecolor(100, 100);

$fontSize = 24;
$font = __DIR__ . '/Fonts/FreeSans.ttf';
$text = 'e';

/* Get letter size before writing. */
$letterBoxSize = imagettfbbox($fontSize, 0, $font, $text);
$letterBoxWidth = max([$letterBoxSize[2], $letterBoxSize[4]]) - min([$letterBoxSize[0], $letterBoxSize[6]]);

/* Write the letter at (50, 50). */
$bbox = imagettftext($tempImage, $fontSize, 0, 50, 50, 0, $font, $text);
$bboxWidth = max([$bbox[2], $bbox[4]]) - min([$bbox[0], $bbox[6]]);

echo 'Width of letter from imagettfbbox: ' . PHP_EOL;
var_dump($letterBoxWidth);

echo 'Width of letter from imagettftext: ' . PHP_EOL;
var_dump($bboxWidth);

The resulting output:

Width of letter from imagettfbbox:
int(19)
Width of letter from imagettftext:
int(20)

How do I get the same width before and after writing the letter?

My PHP version is 7.4.3 and the version of my GD library according to gd_info() is 2.2.5

0

There are 0 best solutions below