Center text on image using PHP GD

流过昼夜 提交于 2019-12-06 15:09:51

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.

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

It took me a long time but I figured out how to center text on an image exactly.

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

You can center a text in an image by getting the half of the image height and width and also the half of the text height and width

You can get the image width and height using imagesx and imagesy respectively.
You can get the text width and height using imagettfbbox method in PHP GD.

After, you get the bound, you can get the text width and text height
text width = right bound on x - left bound on x axis
text height = lower bound on y axis - upper bound on y axis

Then use the image width and height to the get the start offset that will allow your image to be centered
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);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!