我只是试图获得动态文本行的宽度,以添加到使用GD PHP生成的图像。我有点不确定如何。我知道如何使用imageloadfont()加载字体,但我可以使用.ttf文件吗?我想知道使用12号arial字体的文本宽度。当我尝试使用我的ttf文件时,出现错误“读取字体错误,字体标题无效”。如果我需要.gdf文件,我在哪里可以找到字体大小为12 gdf的文件?这是我的代码:
$newfont = imageloadfont("../fonts/arial.ttf");
$font_width = imagefontwidth($newfont);
$font_height = imagefontheight($newfont);
答案 0 :(得分:36)
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手册。
答案 1 :(得分:1)
使用GD2时, imagettfbbox 的字体大小需要在PT中,而不是在具有以下转换的像素中:
($ fontSizeInPixel * 3)/ 4