Creating images on the fly (human verification)

Ok, so yesterday I implemented all the logic behind a anti spam system for pybloxsom comments. The only thing missing was the generation of images on the fly, showing the secret number in a way that humans can read it and also making it weird enough to mess an OCR system.

So, I spent some time investigating PIL, the Python Imaging Library, a set of python modules to manipulate and create images.

Basically what I do is create an small image using PIL, write the number on it and a small grid in two very close colors (grey). You can have a look at the result below in this page.

To display the image, I just use a CGI python script that generates this image from the parameter passed to it like this way:

<img src="/snumber.png?hash=eef334ab8..." />

hash being the filename I was talking about yesterday.

The generation of the image is pretty simple, the code is like:

def generateImage(number):
    font = ImageFont.truetype(fontPath, fontSize)
    im = Image.new("RGB", imageSize, bgColor)
    draw = ImageDraw.Draw(im)

    xsize, ysize = im.size

    # Do we want the grid start at 0,0 or want some offset?
    x, y = 1,1

    draw.setink(gridInk)
    while x <= xsize:
        draw.line(((x, 0), (x, ysize)))
        x = x + xstep
    while y <= ysize:
        draw.line(((0, y), (xsize, y)))
        y = y + ystep

    draw.setink(fontInk)
    draw.text((3, 2), number, font=font)

    return im

which creates the image. The rest of the implementation consist in writing the img to stdout (web) among the HTTP headers.

Well, this is a little hack to do the trick. I believe this code can be further enhaced by, for example, creating a class for generating this kind of images.

You can find the source code here for snumber.png. Just rename it to a name of your choice and make it execute as an CGI. It should work

This and yesterday’s work are a fast hack to avoid spam. It surely can be enhanced. I intend to do it in the next weeks, when I have free time. Feel free to send comments or tell me if you are using it on your system (and if it works). Suggestion, patches and critics are welcome ;-)

Tags// ,
More Reading
Newer// About
comments powered by Disqus