Changing the font of our random number
To control the look and style attributes of our random number, we can replace the imagestring function with the imagettftext function, which lets us control some of the aspects of the font used to render the text.
The imagettftext function takes eight arguments, as described below:
array Imagettftext (int im, int size, int angle, int x, int y, int col,
string fontfile, string text)
im: A reference to an image canvas created using the imagecreate function
size: The height of the font, in pixels
angle: The rotation of the font. Use 0 for standard horizontal display
x: The starting x co-ordinate of where the text will be drawn
y: The starting y co-ordinate of where the text will be drawn
col: A reference to a color created using the imagecolorallocate function
fontfile: The path and filename to the font that the text will be rendered
in (more on this in a minute)
text: The actual string of text to be drawn
So, for our example, we would used the imagettftext function instead of the imagestring function, like this:
Imagettftext($img_number, 30,0,10,33,$black,'trebuchet.ttf',$number);
Notice the seventh argument? It's the location of the true-type font file that will be used to render our text onto the image. In our example, the file trebuchet.ttf is in the same directory as our script. Trebuchet.ttf is contained in the support material at the end of this article.
The Imagettftext file uses the FreeType font support, which is built-in to all of the latest releases of the GD image library. You can read more about the FreeType project here.
Once you have saved the random_number.php file with the new Imagettftext function instead of the imagestriing function, reload the page in your browser. You should see something like this:
Comments