How can the text length be dynamically adjusted to fit the image in PHP?

When displaying text over an image in PHP, it's important to ensure that the text length dynamically adjusts to fit the image without overflowing or getting cut off. One way to achieve this is by calculating the text length and adjusting the font size accordingly. This can be done by measuring the text width using the imagettfbbox function and then scaling the font size based on the image dimensions.

// Set the image path
$imagePath = 'image.jpg';

// Load the image
$image = imagecreatefromjpeg($imagePath);

// Set the text to display
$text = 'Lorem ipsum dolor sit amet';

// Set the font size
$fontSize = 20;

// Calculate the maximum width for the text
$maxWidth = imagesx($image);

// Get the bounding box for the text
$textBox = imagettfbbox($fontSize, 0, 'arial.ttf', $text);

// Calculate the text width
$textWidth = $textBox[2] - $textBox[0];

// Calculate the scaling factor for the font size
$scaleFactor = $maxWidth / $textWidth;

// Adjust the font size based on the scaling factor
$fontSize = $fontSize * $scaleFactor;

// Set the text color
$textColor = imagecolorallocate($image, 255, 255, 255);

// Display the text on the image
imagettftext($image, $fontSize, 0, 10, 20, $textColor, 'arial.ttf', $text);

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

// Free up memory
imagedestroy($image);