How to get the pixel width of a character in the specified font using the imagefontwidth() function in PHP?

The imagefontwidth() function is an inbuilt PHP function that returns the pixel width of a character in a specified font. This function is particularly useful when working with the GD library for creating images with text.

Note: The GD extension must be installed and enabled in PHP to use this function.

Syntax

int imagefontwidth(int $font)

Parameters

The imagefontwidth() function takes only one parameter:

  • $font − The font identifier. For built-in fonts, use values 1, 2, 3, 4, or 5. For custom fonts, use the resource returned by imageloadfont().

Return Value

Returns an integer representing the pixel width of a single character in the specified font.

Example 1: Basic Usage

Here's a simple example showing how to get the width of font size 3 −

<?php
    // Get font width for built-in font size 3
    echo 'Font width: ' . imagefontwidth(3);
?>
Font width: 7

Example 2: Comparing All Built-in Font Sizes

This example demonstrates the pixel width for all built-in font sizes −

<?php
    // Display font widths for all built-in fonts (1-5)
    for ($font = 1; $font <= 5; $font++) {
        echo "Font width for font size $font is: " . imagefontwidth($font) . "<br>";
    }
?>
Font width for font size 1 is: 5
Font width for font size 2 is: 6
Font width for font size 3 is: 7
Font width for font size 4 is: 8
Font width for font size 5 is: 9

Built-in Font Sizes

Font Size Pixel Width Description
1 5 Smallest built-in font
2 6 Small font
3 7 Medium font
4 8 Large font
5 9 Largest built-in font

Conclusion

The imagefontwidth() function provides an easy way to determine character width for text positioning in image creation. Built-in fonts range from 5 to 9 pixels wide, with larger font numbers producing wider characters.

Updated on: 2026-03-15T09:47:57+05:30

673 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements