duandu2980 2012-10-09 18:31
浏览 135
已采纳

图像的错误高度使用Imagettfbbox()使用脚本字体

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);

incorrect image height

  • 写回答

1条回答 默认 最新

  • douzhi4991 2012-10-09 20:47
    关注

    Found the problem, it was my mistake, I had the angle set to 25 instead of 0. So PHP thought the text was going to be written on an angle, which would make the height (and width) measure across the diagonals instead of from top to bottom and side to side.

    Soon as I corrected the angle to 0 it worked fine.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多