What is the purpose of the imagettftext() function in PHP and how is it used?

The imagettftext() function in PHP is used to write text to an image using a TrueType font. This function allows you to customize the font, size, angle, color, and position of the text on the image. It is commonly used in generating dynamic images with text overlays, such as creating custom graphics or adding watermarks to images.

// Create a new image with specified width and height
$image = imagecreate(400, 200);

// Set the background color to white
$bg_color = imagecolorallocate($image, 255, 255, 255);

// Set the text color to black
$text_color = imagecolorallocate($image, 0, 0, 0);

// Specify the TrueType font file and text to be written
$font = 'arial.ttf';
$text = 'Hello, World!';

// Write the text to the image at specified coordinates
imagettftext($image, 20, 0, 50, 100, $text_color, $font, $text);

// Output the image to the browser
header('Content-Type: image/png');
imagepng($image);

// Free up memory
imagedestroy($image);