Calculating Text Width with PHP GD

邮差的信 提交于 2019-12-02 18:24:23

imageloadfont() is used to load user-defined bitmaps. If you just want to use Arial or any other TrueType fonts (.ttf) or OpenType fonts (.otf) (support for the latter in GD lib is buggy), then what you need is imagettftext(). Before using imagettftext() and writing text to your image though, you first need to know if it will fit. To know this you just need to call imagettfbbox() and pass it the font size, the angle of the text (0 for horizontal text), the path to your .ttf or .otf font file and the string of text itself and it will return an array with 8 elements representing four points making the bounding box of the text (check PHP manual for specifics). You can then reference those array elements and perform calculations in order to know the width and height that that particular string of text will take up. You can then use those values to create an image with a specific width and height that will allow for the text to be displayed in its entirety.

Here is a simple script that accomplishes what you are trying to do in order to get you started:

<?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);

?>

Change values accordingly to fit your needs. Don't forget to read the PHP manual.

With GD2, the imagettfbbox's font size need to be in PTs, not in Pixels with the following convert:

($fontSizeInPixel * 3) / 4

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!