PHP Image Text Drawing: Coordinate and Size Measurement, Horizontal Centering of Text in PHP Images
When drawing text onto an image in PHP, sometimes you need the text to be centered. In such cases, you can use the imagettfbbox function.
Example:
//1. Configure the image path |
imagettfbbox — Gets the bounding box of a text using TrueType fonts
Parameter Description ¶
imagettfbbox ( float $size , float $angle , string $fontfile , string $text ) : array
This function calculates and returns the pixel size of a virtual box surrounding TrueType text.
size: Font size in pixels.
angle: Angle size in degrees by which the text will be measured.
fontfile: The filename of the TrueType font. Depending on the GD library version used by PHP, it may attempt to search for filenames not starting with ‘/‘ and append the ‘.ttf’ suffix, and search library-defined font paths.
text: The string to be measured.
Return Value:
imagettfbbox() returns an array with 8 elements representing the four corners of the text’s bounding box:
0 Lower left X position
1 Lower left Y position
2 Lower right X position
3 Lower right Y position
4 Upper right X position
5 Upper right Y position
6 Upper left X position
7 Upper left Y position