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

时间:2014-04-07 19:08:56

标签: 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']);

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

4 个答案:

答案 0 :(得分:7)

结帐imagettfbboxhttp://www.php.net/manual/en/function.imagettfbbox.php。它将为您提供要渲染的文本范围。然后用简单的算法将其置于图像中心。

答案 1 :(得分: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);

imageftbbox documentation

答案 2 :(得分:0)

我花了很长时间,但我想出了如何准确地将文字放在图像上。

list($left,, $right) = imageftbbox(18, 0, 'minecraft.ttf', $_GET['description']);
$dwidth = $right - $left;
$pos = (HALF_OF_IMAGE_WIDTH - $nwidth / 2);

答案 3 :(得分:0)

您可以通过获取图像高度和宽度的一半以及文本高度和宽度的一半来使图像居中于图像中

您可以分别使用imagesximagesy获取图片的宽度和高度 您可以使用PHP GD中的imagettfbbox方法获取文本宽度和高度。

之后,你得到了界限,你可以得到文字宽度和文字高度
text width =右边界x - 左边界x轴
文本高度= y轴上的下限 - y轴上限

然后使用图像宽度和高度来获得允许图像居中的起始偏移量 start_x_offset =(imagewidth - textwidth)/ 2;
start_y_offset =(imageheight - textheight)/ 2;

// Get image dimensions
$image_width = imagesx($image);
$image_height = imagesy($image);

$text_bound = imageftbbox($font_size, $angle, $font, $text);

//Get the text upper, lower, left and right corner bounds
$lower_left_x =  $text_bound[0]; 
$lower_left_y =  $text_bound[1];
$lower_right_x = $text_bound[2];
$lower_right_y = $text_bound[3];
$upper_right_x = $text_bound[4];
$upper_right_y = $text_bound[5];
$upper_left_x =  $text_bound[6];
$upper_left_y =  $text_bound[7];


//Get Text Width and text height
$text_width =  $lower_right_x - $lower_left_x; //or  $upper_right_x - $upper_left_x
$text_height = $lower_right_y - $upper_right_y; //or  $lower_left_y - $upper_left_y

//Get the starting position for centering
$start_x_offset = ($image_width - $text_width) / 2;
$start_y_offset = ($image_height - $text_height) / 2;

// Add text to image
imagettftext($image, $font_size, $angle, $start_x_offset, $start_y_offset, $color, $font, $text);