【问题标题】:Calculating Text Width with PHP GD使用 PHP GD 计算文本宽度
【发布时间】:2012-07-26 16:05:00
【问题描述】:

我只是想获取动态文本行的宽度,以添加到使用 GD PHP 生成的图像中。我有点不确定如何。我知道如何使用 imageloadfont() 加载字体,但我可以使用 .ttf 文件吗?我想知道使用 12 号 arial 字体的文本宽度。当我尝试使用我的 ttf 文件时,我收到错误“读取字体错误,字体标题无效”。如果我需要 .gdf 文件,我在哪里可以找到字体大小为 12 的 gdf ​​文件?这是我的代码:

$newfont = imageloadfont("../fonts/arial.ttf");
$font_width = imagefontwidth($newfont);
$font_height = imagefontheight($newfont);

【问题讨论】:

标签: php fonts gd


【解决方案1】:

imageloadfont() 用于加载用户定义的位图。如果您只想使用 Arial 或任何其他 TrueType 字体 (.ttf) 或 OpenType 字体 (.otf)(GD lib 中对后者的支持是错误的),那么您需要的是imagettftext()。不过,在使用imagettftext() 并将文本写入您的图像之前,您首先需要知道它是否适合。要知道这一点,您只需调用imagettfbbox() 并将字体大小、文本角度(水平文本为 0)、.ttf 或 .otf 字体文件的路径以及文本字符串本身传递给它返回一个包含 8 个元素的数组,这些元素代表构成文本边界框的四个点(具体请查看 PHP 手册)。然后,您可以引用这些数组元素并执行计算,以了解该特定文本字符串将占用的宽度和高度。然后,您可以使用这些值创建具有特定宽度和高度的图像,以允许文本完整显示。

这是一个简单的脚本,它完成了您尝试做的事情以帮助您入门:

<?php # Script 1

/*
 * This page creates a simple image.
 * The image makes use of a TrueType font.
 */

// Establish image factors:
$text = 'Sample text';
$font_size = 12; // Font size is in pixels.
$font_file = 'Arial.ttf'; // This is the path to your font file.

// Retrieve bounding box:
$type_space = imagettfbbox($font_size, 0, $font_file, $text);

// Determine image width and height, 10 pixels are added for 5 pixels padding:
$image_width = abs($type_space[4] - $type_space[0]) + 10;
$image_height = abs($type_space[5] - $type_space[1]) + 10;

// Create image:
$image = imagecreatetruecolor($image_width, $image_height);

// Allocate text and background colors (RGB format):
$text_color = imagecolorallocate($image, 255, 255, 255);
$bg_color = imagecolorallocate($image, 0, 0, 0);

// Fill image:
imagefill($image, 0, 0, $bg_color);

// Fix starting x and y coordinates for the text:
$x = 5; // Padding of 5 pixels.
$y = $image_height - 5; // So that the text is vertically centered.

// Add TrueType text to image:
imagettftext($image, $font_size, 0, $x, $y, $text_color, $font_file, $text);

// Generate and send image to browser:
header('Content-type: image/png');
imagepng($image);

// Destroy image in memory to free-up resources:
imagedestroy($image);

?>

相应地更改值以满足您的需求。不要忘记阅读 PHP 手册。

【讨论】:

  • 对不起,this thing doesn't work。这是它使用文本 "666"(或任何其他数字 AFAIK)和 Courier New 字体生成的。它也不适用于其他字体 - 总是在这里和那里剪掉一些东西。我知道 PHP 背后的人不称职不是你的错,但仍然是不赞成的。
  • Another example 我强调了哪里出了问题。
  • 它帮助了我,尽管有像q这样的文字被删减
【解决方案2】:

使用 GD2,imagettfbbox 的字体大小需要以 PT 为单位,而不是以像素为单位,并进行以下转换:

($fontSizeInPixel * 3) / 4

【讨论】:

  • 或者只是$pixel_width * .75,不用乘除。
猜你喜欢
  • 1970-01-01
  • 2010-12-07
  • 2010-09-12
  • 2011-03-18
  • 2011-11-25
  • 1970-01-01
  • 1970-01-01
  • 2013-03-23
相关资源
最近更新 更多