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.
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!