3
votes

I want to center the text I add to my image using :

imagettftext($image, 85, 0, 250, 350, $color, $font, $txt );

I tried something like this :

$fontwidth1 = imagefontwidth($font);
$center1 = (imagesx($image)/2) - ($fontwidth1*(strlen($txt)/2));

However unfortunately it's not working. The imagefontwidth($font) part does not work :(

Anyone has faced this issue before and know an solution / alternative method ?

1
Can you be more specific than "does not work"? What happens and what do you expect to happen? - Jeffrey Bosboom
(imagesx($image)/2) works gives correct value. ($fontwidth1*(strlen($txt)/2)) Returns 0. - BRDS
And yes i set all other variables properly. - BRDS
I suggest using imagettfbbox() - Austin Brunkhorst
Thanks Austing, great hint. How can I add this answer ? - BRDS

1 Answers

4
votes

The function imagefontwidth works best with fixed-width fonts. Like Austin Brunkhorst said, the most reliable way to get centered text uses imagettfbbox, like so:

$bbox = imagettfbbox(85, 0, $font, $txt);
$center1 = (imagesx($image) / 2) - (($bbox[2] - $bbox[0]) / 2);