How to center a letter with imagettftext?


I had recently built a GDPR plugin for a customer and had to replace the gravatars used by WordPress.

I created an image with PHP and then placed the letter with imagettftext. It turned out to be especially difficult (at least for me) to center the letter.

Currently I determined the width of the letter with imagettfbbox and subtract half of it and then subtract the result from half the width of the image. But this does not work with every letter, so I always have to readjust.

$font = 'font-family.ttf';

$type_space = imagettfbbox( $font_size, 0, $font, $letter );

$letter_width  = abs( $type_space[4] - $type_space[6] );
$letter_height = abs( $type_space[5] - $type_space[1] );

$x = ( $image_width / 2 ) - ( $letter_width / 2 );
$y = ( $image_height / 2 ) + ( $letter_height / 2 );

imagettftext( $image, $font_size, 0, $x, $y, $text_color, $font, $letter );

The font size is determined automatically so that it is bigger or smaller depending on the avatar size:

$font_size = abs( $image_height / 2.5 );

I found 2.5 to be optimal to read on all image sizes. Unfortunately, this does not apply to all initial letters. With the font family Poppins only the letters W, P and K are affected.

Maybe someone has a hint here?

You want to create your own picture with PHP? Have a look at the PHP manual.


No Comments Yet