Quite a cryptic title, but if you haven’t guessed, were talking about Images. This being a Python article that’s what we're using! If you’ve never thought about it, or -- even better -- if you didn’t know it was possible then you’re in for a nice surprise; not only can Python do this but it’s pretty good at it, too. Actually, Python works well with graphics in general, but for now we’re sticking to the 2D kind.
Last but not least: You may or may not have noticed those funky little images some websites use to stop automated signups and etc. No? Never mind if you haven't because that's what we're about to do.
def verify(): image = Image.new('RGB', (125, 40), (255, 255, 255)) font = ImageFont.truetype('Verdana.ttf', 25) draw = ImageDraw.Draw(image) draw.text((5, 5), sample(), font = font, fill = (0, 0, 0)) image.save('verify.gif')
if __name__ == '__main__': verify()
There are a few differences between this example and the others we've talked about so far. Primarily the three modules ImageDraw, ImageFont and random and the two functions sample() and verify().
Why have two functions? We could have just as easily done this inside verify couldn't we?
The thing is, sooner or later everyone ends up rewriting something they wrote for some other project. One of the nice things about using Python is it encourages you to write clean, reusable, modular code. Which is of course the main reason for the sample() function; since it just returns a string of random letters you could also use it to automate password generation!
Short and sweet, all sample() does is pick five letters at random from the string 'ascii' using random.sample() and returns them as a string.
verify() on the other hand has a little more going for it. This one unlike any of the other examples we've looked at starts off by creating a brand spanking new image instead of opening one! We're going to write our random letters onto this in a second, but first we need to load the font we want to use, for this we're using the ImageFont module. We then create a new instance of ImageDraw.Draw() which is used to draw the sample() string on the image!
Anyway it's pretty safe to assume you have a good idea why this could be useful by now. You should also know enough to get started using PIL with your own images. Slap open up your Python shell and get playing!
Liked this article? Then you'll probably find these links interesting too!
Note: All the sample programs shown and discussed in this article where tested on Windows XP running Python 2.3 with PIL 1.4 and are meant only as examples.