Not Really a Blog

August 5, 2004

Creating images on the fly (human verification)

Filed under: Programming — Tags: — jesus @ 12:24

Ok, so yesterday I
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
, 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 ="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

    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.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 ;-)

About these ads

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

The Shocking Blue Green Theme. Blog at


Get every new post delivered to your Inbox.

Join 2,855 other followers

%d bloggers like this: