There are lots of ways to write that. Some are easier than others but if they are easier, they have weaknesses that could make your security easier for a machine to bypass.
Technique #1: Draw 100 images. Name them 1.gif, 2.gif, 3,gif, etc. Pick a random number between 1-100 and display <img src="<? print "$random"; ?>.gif"> and then input some text. See if the text matches an array with the right answer for that random number. The problem with this technique is that a machine can look at your HTML and find the "IMG SRC" tag and figure out which graphic is being shown and provide the right answer. If your web site has something valuable, it might be worth it for someone to send 2-3 hours to break your security.
Technique #2: Pick a random number from a billion to a trillion. IMG SRC tag pulls the graphic from a script like this: <img src="get_graphic.php?r=<? echo $r; ?>"> The script uses some formula that you make up to determine which of your 100 graphics to show. Input the text and compare the text to an array to see if there is a match. With lots of work, people can figure out your formula and determine what string goes with your random number. Again, if your web site is worth it, people might be willing to take the time to break your security.
Technique #3: This is the hardest to program and the most CPU intensive on your server but it's pretty much unbreakable. Pick a random string of text. Build a graphic with GD or ImageMagick (I prefer Image Magick) and put the text on the graphic in random fonts. Randomly distort the image. Include a hidden field with the text encrypted with md5 like this: <input type=hidden name="secret_text" value="<? echo md5($secret); ?>"> Then input the user's text. If the md5 of the user's text is the same as the secret_text string, then the user must have entered the right string. This is pretty much unbreakable.
Good luck.