When performing image processing, dynamically centering the text on the picture is one of the common needs. PHP's GD library provides a series of functions to help developers handle such tasks, among which imagefontwidth() and imagestring() are two important functions. This article will use a simple example to illustrate how to use these two functions to achieve horizontal centering display of text.
This function returns the pixel value of the specified font width. Font numbers are predefined by GD, from 1 to 5, the larger the number, the larger the font.
int imagefontwidth(int $font);
This function is used to write a string to an image.
bool imagestring(GdImage $image, int $font, int $x, int $y, string $string, int $color);
Parameter explanation:
$image : Image resource
$font : Font number (1~5)
$x , $y : The starting position of text writing
$string : The text to be written
$color : color index value
Let’s take a picture with a width of 400 pixels and a height of 100 pixels as an example, and center a paragraph of text into the picture.
<?php
// Create a canvas
$width = 400;
$height = 100;
$image = imagecreate($width, $height);
// Set color
$background_color = imagecolorallocate($image, 255, 255, 255); // White background
$text_color = imagecolorallocate($image, 0, 0, 0); // Black text
// Text to be written
$text = "Welcome to visit m66.net";
$font = 5;
// Calculate text width
$text_width = imagefontwidth($font) * strlen($text);
// calculateXcoordinate,Center the text
$x = ($width - $text_width) / 2;
// Ycoordinate(Vertical position)Customizable,Here is simply set to vertical center
$y = ($height - imagefontheight($font)) / 2;
// Write text
imagestring($image, $font, $x, $y, $text, $text_color);
// Output image to browser
header("Content-Type: image/png");
imagepng($image);
// Free memory
imagedestroy($image);
?>
Font limitations : imagefontwidth() only applies to built-in fonts used by imagestring() . If you need to have more granular control over text style and position, you should consider imagettftext() .
Multi-byte characters : strlen() is inaccurate when processing Chinese. You can use mb_strlen() instead, or estimate the character width.
Performance optimization : For frequently generated image content, consider the cache mechanism to avoid repeated operations.
This method is suitable for dynamically generating verification codes, image watermarks, QR code captions, or image text synthesis on custom short URL platforms such as https://m66.net .
Through a simple combination of several functions, the practical and flexible text centering function can be achieved, greatly improving the professionalism of user experience and image presentation.