How can imagettftext be utilized in PHP to overcome font size limitations in dynamic graphics?

When using imagettftext in PHP to generate dynamic graphics, font size limitations may arise when trying to display text at larger sizes. One way to overcome this limitation is by dynamically adjusting the font size based on the dimensions of the image to ensure the text fits within the boundaries.

// Set the desired font size
$fontSize = 30;

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

// Define the font file path
$fontFile = 'arial.ttf';

// Calculate the maximum font size that fits within the image dimensions
while ($fontSize > 0) {
    $bbox = imagettfbbox($fontSize, 0, $fontFile, 'Sample Text');
    $textWidth = $bbox[2] - $bbox[0];
    $textHeight = $bbox[1] - $bbox[7];

    if ($textWidth < 400 && $textHeight < 200) {
        break;
    }

    $fontSize--;
}

// Set the font size and color
$fontColor = imagecolorallocate($image, 255, 255, 255);
imagettftext($image, $fontSize, 0, 10, 50, $fontColor, $fontFile, 'Sample Text');

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