The syntax of imagefontwidth() is very simple:
int imagefontwidth(int $font)
The $font parameter is an integer that specifies the font number.
PHP has several built-in fonts for image functions. The effective range of these font numbers is usually from 1 to 5 , and each number corresponds to a font of different sizes:
1 : Minimum font, width of 6 pixels
2 : Width is 8 pixels
3 : Width is 10 pixels
4 : Width is 12 pixels
5 : Maximum font, width of 16 pixels
When you call imagefontwidth() , if the passed font number exceeds this range (for example, 0 or above), the function will return false , indicating that it is invalid.
<?php
$font = 3;
$width = imagefontwidth($font);
echo "Font $font The width is: $width Pixels";
?>
Output:
Font 3 The width is: 10 Pixels
These fonts are fixed fonts that come with the GD library, not TTF or OTF font files. Their style is relatively simple, but it is sufficient for many lightweight image processing scenarios.
If you need richer font styles (like custom font files), consider using the imagettftext() function, which allows to use .ttf font files and specify font size and angle, but that has nothing to do with imagefontwidth() .
Suppose you want to dynamically calculate the total width of a piece of text so that it can be centered in the image:
<?php
$text = "Hello M66";
$font = 4;
$width = imagefontwidth($font) * strlen($text);
$image = imagecreate(300, 50);
$white = imagecolorallocate($image, 255, 255, 255);
$black = imagecolorallocate($image, 0, 0, 0);
$x = (300 - $width) / 2;
$y = (50 - imagefontheight($font)) / 2;
imagestring($image, $font, $x, $y, $text, $black);
imagepng($image, "https://m66.net/output.png");
imagedestroy($image);
?>
In this example, we obtain the pixel width required for the text through imagefontwidth() , and then realize the centered display of the text in the image.
The valid font number of the imagefontwidth() function is from 1 to 5 , which provides an easy way to handle bitmap fonts. These built-in fonts and related functions are very practical tools in scenarios where text information is simply and quickly embedded in images. However, for higher quality and more design-oriented text presentations, you should consider using functions that support TrueType fonts.