Writing Text On An Image With GD

/ PHP / by Paul Robinson / 0 comments
This post was published back on June 18, 2010 and may be outdated. Please use caution when following older tutorials or using older code. After reading be sure to check for newer procedures or updates to code.

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:

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.

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.

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.

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:

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

I'll keep your WordPress site up-to-date and working to its best.

Find out more