使用PHP GD在图像上居中显示文本

The*_*ony 2 php gd php-gd

所以我正在创建一个横幅生成器.

我将在中间添加文本,但希望它完全位于中心.我知道imagettftext可以用来写入横幅,但这不会使它居中.

一个可能的解决方案可能是找到文本的宽度,然后使用一半从横幅宽度的一半取出,但我不知道如何做到这一点.

我使用的是PHP-GD,不想使用其他任何我必须安装的东西.

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

上面的代码是上面的结果.小字符串很好,但一定有问题,因为一旦它们变长,它就会失败.

Kry*_*ten 7

查看imagettfbbox:http://www.php.net/manual/en/function.imagettfbbox.php.它将为您提供要渲染的文本范围.然后,这是一个简单的算术,以在您的图像上居中.


Tyl*_*ler 5

您可以通过从外边界获取宽度imageftbbox然后将其除以2来使文本居中,以获得将文本置于图像中心的偏移.

// 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);
Run Code Online (Sandbox Code Playgroud)

imageftbbox文档

  • `$y = $centerY - top_offset;` 需要为 `$y = $centerY + $top_offset;` (2认同)