How can the alignment of text be managed in PHP when adding it to images, especially for centering text within an image?

When adding text to images in PHP, the alignment of the text can be managed by calculating the position where the text should start to ensure it is centered within the image. This can be achieved by determining the width of the text and the image, then calculating the x-coordinate where the text should start to be centered horizontally.

// Create a new image with specified width and height
$image = imagecreatetruecolor(800, 600);

// Define text color and font size
$textColor = imagecolorallocate($image, 255, 255, 255);
$fontSize = 20;

// Define the text to be added to the image
$text = "Centered Text";

// Calculate the position to center the text horizontally
$textWidth = imagefontwidth($fontSize) * strlen($text);
$x = (imagesx($image) - $textWidth) / 2;
$y = 300; // Y-coordinate for vertical centering

// Add the centered text to the image
imagestring($image, $fontSize, $x, $y, $text, $textColor);

// Output the image
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);