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

图像的错误高度使用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.

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

报告相同问题?

悬赏问题

  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题