How can one dynamically adjust the image size in PHP GD based on the length of the text being output?

When outputting text on an image using PHP GD, it's important to dynamically adjust the image size based on the length of the text to ensure that the text fits properly within the image. One way to solve this is by calculating the width and height of the text using the `imagettfbbox()` function, then adjusting the image size accordingly before outputting the text onto the image.

<?php
$text = "Hello, World!";
$font = 'path/to/font.ttf';
$fontSize = 12;

// Create a bounding box for the text
$textBox = imagettfbbox($fontSize, 0, $font, $text);
$textWidth = $textBox[2] - $textBox[0];
$textHeight = $textBox[1] - $textBox[7];

// Create an image with appropriate dimensions
$image = imagecreatetruecolor($textWidth, $textHeight);

// Add text to the image
$black = imagecolorallocate($image, 0, 0, 0);
imagettftext($image, $fontSize, 0, 0, $textHeight, $black, $font, $text);

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

// Free up memory
imagedestroy($image);
?>