Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center text on image using PHP GD

Tags:

php

gd

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.

like image 305
ThePixelPony Avatar asked Jul 11 '26 01:07

ThePixelPony


2 Answers

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

like image 107
Tyler Avatar answered Jul 15 '26 16:07

Tyler


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.

like image 31
Kryten Avatar answered Jul 15 '26 15:07

Kryten