繁体   English   中英

使用PHP GD计算文本宽度

[英]Calculating Text Width with PHP GD

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

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

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手册。

对于GD2, imagettfbbox的字体大小需要在PT中,而不是在具有以下转换的像素中:

($ fontSizeInPixel * 3)/ 4

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM