Search code examples
phpgdphp-gd

Center text on image using PHP GD


So I am creating a banner generator.

I will be adding text in the middle, but would like it to be exactly in the center. I know that imagettftext can be used to write onto the banner, but that won't center it.

A likely solution could be to find the width of the text and then use half of it taken away from half of the banner width, but I've got no idea about how to do this.

I am using PHP-GD and do not want to use anything else I will have to install.

imagettftext($img, 14, 0, (468 - ((strlen($_GET['description']) * imagefontwidth(imageloadfont('minecraft.ttf'))) / 1)), 85, imagecolorallocate($img, 0, 0, 0), 'minecraft.ttf', $_GET['description']);

The code above is making the result above. It is fine with small strings but there must be something wrong since as soon as they become long, it fails.


Solution

  • Check out imagettfbbox: http://www.php.net/manual/en/function.imagettfbbox.php. It will give you the extents of the text you wish to render. Then it's simple arithmetic to center that on your image.