使用PHP GD计算文本宽度

19

我只是想获取动态文本行的宽度,并将其添加到使用GD PHP生成的图像中。但我有些不确定如何做。我知道如何使用imageloadfont()加载字体,但我能不能使用.ttf文件呢?我想知道使用大小为12的arial字体的文本宽度。当我尝试使用我的ttf文件时,出现错误“Error reading font, invalid font header。”如果我需要一个.gdf文件,那么在哪里可以找到一个大小为12的gdf文件呢?以下是我的代码:

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

2
请查看imagettfbboximagettftext - Vatev
2个回答

44

imageloadfont()函数用于加载用户自定义的位图字体。如果你只想使用Arial或其他TrueType字体(.ttf)或OpenType字体(.otf)(在GD库中支持后者有漏洞),那么你需要的是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手册。


抱歉,但是这个东西不起作用。使用文本“666”(或其他数字,据我所知)和 Courier New 字体生成的结果如上图所示。它在其他字体上也无法正常工作 - 总是会在这里或那里切掉一些东西。我知道这不是你的错,因为 PHP 背后的人们很无能,但还是要点个踩。 - Tomáš Zato
另一个例子,在这里我标出了问题所在。 - Tomáš Zato
它帮助了我,即使文本中有割裂的部分,比如 q - arun
$font_size = 12; // 字体大小以像素为单位。 这是以点为单位的字体大小,而不是像素。 - Merijndk

1

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

($fontSizeInPixel * 3) / 4


4
可以直接写成 $pixel_width * .75,不需要先乘后除。 - Exit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接