How can one effectively center text both horizontally and vertically using ImageTTFText() in PHP?

To center text both horizontally and vertically using ImageTTFText() in PHP, you can calculate the position based on the text size and image dimensions. This involves determining the text width and height using imagettfbbox() and then calculating the x and y coordinates to place the text at the center.

// Set text and font size
$text = "Centered Text";
$font_size = 20;

// Get text dimensions
$text_box = imagettfbbox($font_size, 0, 'path/to/font.ttf', $text);
$text_width = abs($text_box[4] - $text_box[0]);
$text_height = abs($text_box[5] - $text_box[1]);

// Calculate center position
$x = (imagesx($image) - $text_width) / 2;
$y = (imagesy($image) + $text_height) / 2;

// Add centered text to image
imagettftext($image, $font_size, 0, $x, $y, $text_color, 'path/to/font.ttf', $text);