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.

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

报告相同问题?

悬赏问题

  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写