Writing Text On An Image With GD
Writing on an pre-existing image using GD can seem complicated at first, but to be honest it is quite easy. With the code being fairly small I’m going to go through each line & then post the code in it’s entirety at the end.
Let’s take a look at the first line:
1 |
$image = imagecreatefromjpeg('path/to/image'); |
This line simply loads our image into a GD resource so we can manipulate it. You can use any of the other imagecreatefrom
functions if you aren’t using a jpeg.
1 |
$black = imagecolorallocate($image, 0, 0, 0); |
Now we allocate a color within the image for our text. The zeros are RGB values so feel free to change them to whatever you like.
1 |
imagefttext($image, 16, 0, 50, 50, $black, './verdana.ttf', 'This is text'); |
imagefttext
allows us to write on our image. Parameters are as follows. A GD image handle. Font pixel size if using GD, point size if using GD2. Angle of the text. Position X. Position Y. Color index. The path to a font file. The text to write. One thing to note is that the X & Y positions are from approximately the bottom left rather than the top left.
1 2 3 |
header('Content-type: image/jpeg'); imagejpeg($image); imagedestroy($image); |
These last few lines are pretty simple so I’ve put them together. header()
sets the content type so the browser will show the image. imagejpeg()
sends the output to the browser, and imagedestroy()
destroys the image handle as we no longer need it.
Here is the whole code:
1 2 3 4 5 6 |
$image = imagecreatefromjpeg('path/to/image'); $black = imagecolorallocate($image, 0, 0, 0); imagefttext($image, 16, 0, 50, 50, $black, './verdana.ttf', 'This is text'); header('Content-type: image/jpeg'); imagejpeg($image); imagedestroy($image); |
You can easily integrate this code into a uploader by using parts of the code from my previous tutorial on how to make square thumbnails. You could also replace the header()
& imagejpeg()
functions here for the ones used in the latter to save out the files rather than displaying them.
I hope this tutorial has helped you out. Let me know if you have any questions or problems using the comments.