imagettftext fit to image width

$targetWidth = 400; // Your image width
$fontSize = 20;     // Initial test size
$bbox = imagettfbbox($fontSize, 0, $fontPath, $text);
$currentWidth = abs($bbox[4] - $bbox[0]);

$scale = $targetWidth / $currentWidth;
$finalFontSize = $fontSize * $scale;

imagettftext($image, $finalFontSize, 0, $x, $y, $color, $fontPath, $text);

imagettftext display large text same as in browser with fixed font size without cutting

// 1. Setup
$text = "Large Text";
$font = 'path/to/font.ttf';
$size = 40; // Fixed font size in points
$angle = 0;

// 2. Get text dimensions to prevent cutting
$box = imagettfbbox($size, $angle, $font, $text);

// Coordinates for bounding box
$textWidth = $box[2] - $box[0];
$textHeight = $box[1] - $box[7];

// 3. Center Text
$imageWidth = 500;
$imageHeight = 200;
$x = ($imageWidth - $textWidth) / 2;
$y = ($imageHeight + $textHeight) / 2; // Position based on baseline

// 4. Render
$image = imagecreatetruecolor($imageWidth, $imageHeight);
$color = imagecolorallocate($image, 255, 255, 255);
imagettftext($image, $size, $angle, $x, $y, $color, $font, $text);
