Center text on image using PHP GD

ThePixelPony picture ThePixelPony · Apr 7, 2014 · Viewed 14.7k times · Source

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.

Answer

Tyler picture Tyler · Jan 21, 2016

You can center the text by getting the width from the outer boundaries from imageftbbox then divide this by two to get an offset that will center the text in the image.

// Get image dimensions
  $width = imagesx($image);
  $height = imagesy($image);
// Get center coordinates of image
  $centerX = $width / 2;
  $centerY = $height / 2;
// Get size of text
  list($left, $bottom, $right, , , $top) = imageftbbox($font_size, $angle, $font, $text);
// Determine offset of text
  $left_offset = ($right - $left) / 2;
  $top_offset = ($bottom - $top) / 2;
// Generate coordinates
  $x = $centerX - $left_offset;
  $y = $centerY + $top_offset;
// Add text to image
  imagettftext($image, $font_size, $angle, $x, $y, $color, $font, $text);

imageftbbox documentation