When drawing text onto an image in PHP, sometimes you need the text to be centered. In such cases, you can use the imagettfbbox function.
Example:

//1. Configure the image path
$src = 'local path to image';
//2. Get image information
$info = getimagesize($src);
//3. Get image type by number
$type = image_type_to_extension($info[2], false);
//4. Create an image in memory with the same type as the original image
$fun = "imagecreatefrom" . $type;
//5. Copy the image to memory
$image = $fun($src);
$font = "font.ttf";
$content='Text content here';
$fontSize = 40;//Pixel font size
//Set font color and transparency
$color = imagecolorallocatealpha($image, 0,0,0,0);
//Calculate the position coordinates of text margin
$fontBox = imagettfbbox($fontSize, 0, $font, $content);
//Handle text horizontal centering. $info[0] is the total width of the image, obtained using the getimagesize($src) function.
imagettftext($image, $fontSize, 0, ceil(($info[0]- $fontBox[2]) / 2), $merchnameHpx, $color, $font, $content);
$fun = "image" . $type;
//Save the image locally
$resultImg_2 = uniqid() . 'bg_res.' . $type;
$fun($image, '../local save path/' . $resultImg_2);
/*Destroy the image*/
imagedestroy($image);


imagettfbbox — Gets the bounding box of a text using TrueType fonts

Parameter Description ¶
imagettfbbox ( float $size , float $angle , string $fontfile , string $text ) : array
This function calculates and returns the pixel size of a virtual box surrounding TrueType text.

size: Font size in pixels.
angle: Angle size in degrees by which the text will be measured.
fontfile: The filename of the TrueType font. Depending on the GD library version used by PHP, it may attempt to search for filenames not starting with ‘/‘ and append the ‘.ttf’ suffix, and search library-defined font paths.
text: The string to be measured.


Return Value:
imagettfbbox() returns an array with 8 elements representing the four corners of the text’s bounding box:
0 Lower left X position
1 Lower left Y position
2 Lower right X position
3 Lower right Y position
4 Upper right X position
5 Upper right Y position
6 Upper left X position
7 Upper left Y position