How can the imagestring() function be used effectively to write text on an image in PHP?

To write text on an image in PHP using the imagestring() function, you need to specify the image resource, font size, x and y coordinates, text color, and the actual text you want to write. This function allows you to add text directly onto an image without the need for external libraries or tools. By adjusting the parameters, you can customize the appearance and position of the text on the image.

// Create a new image
$image = imagecreatefromjpeg('image.jpg');

// Set the font size, x and y coordinates, text color, and the text to be written
$font_size = 12;
$x = 10;
$y = 20;
$text_color = imagecolorallocate($image, 255, 255, 255);
$text = 'Sample Text';

// Write the text on the image
imagestring($image, $font_size, $x, $y, $text, $text_color);

// Output the image
header('Content-type: image/jpeg');
imagejpeg($image);

// Free up memory
imagedestroy($image);