I'm generating a PNG image (transparent background) of some text on the fly. The text will be whatever the user typed, using English 111 Vivace BT (a script) as the font.
The image will always be 100px tall by 200px wide, regardless of how large the text is. I want the text to be horizontally centered and positioned as close to the top of the image as possible.
This all works generally fine except that imagettfbbox() appears to be returning incorrect points for the bounding box, it thinks the text is taller than it really is, and therefore some blank space is appearing at the top of the image, before the text.
Please see the attached example png, I drew some red guidelines to demonstrate the problem. The left side shows a guideline that is 38px tall, which is what imagettfbbox() thinks is the height of the text. The right side shows a line measured against the text itself, and it's only 26px tall.
is there a more accurate way to get the box? Or have I made some other mistake here?
$text = "A";
$fontSize = 15;
$font = "e111viva-webfont.ttf";
$textColor = convertHexToRGB( "000000" );
$angle = 25;
$image = imagecreatetruecolor( 200, 100 );
$textDimensions = imagettfbbox($fontSize, $angle, $font, $text);
$textHeight = abs($textDimensions[7]);
$textWidth = abs($textDimensions[0]) + abs($textDimensions[2]); // lower left X + lower right X
$textLeft = (200 - $textWidth) / 2;
// center horizontally
$textX = $textDimensions[0] + (imagesx($image) / 2) - ($textDimensions[4] / 2) - 25;
$textY = $textDimensions[1] * 2;
imagesavealpha($image, true);
imagealphablending($image, true);
$transparentColor = imagecolorallocatealpha($image, 0, 0, 0, 127);
$fillResult = imagefill($image, 0, 0, $transparentColor);
$textColor = imagecolorallocate($image, $textColor["r"], $textColor["g"], $textColor["b"]);
$ttfTextResult = imagettftext($image, $fontSize, 0, $textLeft, $textHeight, $textColor, $font, $text);
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);