The issue is, that when using imagettfbbox
to calculate text dimensions, too small rectangle is returned when input text begins with numbers. This is my code:
$fontSize = 150;
$font = "font/courier_new.ttf";
$text = $_GET["text"];
//Determine font dimensions
$bbox = imagettfbbox($fontSize, 0, $font, $text);
$bbox["width"]= abs($bbox[4]-$bbox[0]);
$bbox["height"]= abs($bbox[5]-$bbox[1]);
$im = imagecreatetruecolor($bbox["width"], $bbox["height"]);
echo "<b>Image size:</b>\n";
print_r($bbox);
// This part makes transparent background
imagesavealpha($im, true);
$bg = imagecolorallocatealpha($im, 254, 254, 254,127);
$text_color= imagecolorallocate($im, 0, 0, 0);
imagealphablending($im, false);
imagefilledrectangle($im, 0, 0, imagesx($im), imagesy($im), $bg );
imagealphablending($im, true);
header("X-Img-Size: ".$bbox["width"]."x".$bbox["height"]."");
imagettftext($im, $fontSize, 0, 0, $bbox["height"], $text_color, $font, $text);
// This is output
header("Content-Type: text/html");
ob_start();
imagepng($im);
$image_data = ob_get_contents();
ob_end_clean();
imagedestroy($im);
echo "<img src=\"data:image/png;base64,".base64_encode($image_data)."\" />";
These are results I get for different input text:
How can I fix that?
peterjwest3
's answer with a proposed fix. The writer of the function must have taken some shortcuts... It appears to useFT_BBox
, except that this would "give the glyph's descender" correctly. – Marquardtx
andy
coordinates and assumed[0, 0]
when drawing. If I usex
andy
from the function, it works as it should: u8.8u.cz/testing/ttf/extended.php – Detriment