Official ObjectGraph Blog

Friday, January 19, 2007

PIL on captcha - Transparency and Masking for CAPTCHA

It seems that there are no good introductions for how to create transparent image text. However we want it for common image module like CAPTCHA which is an image authentication method. It's easy to just draw text on image, but in order to rotate the text, you have to rotate the image with the text. I think one of the solution is using mask after rotation. You need 3 images to do this.

1. Background

2. Text

3. Mask

2 and 3 must be in a same size, and when you "paste" the text, you can specify the mask as the extra paramter.

This is simple exapmle, to rotated "Hello" on the background hello.jpg


import Image,ImageDraw,ImageFont

# Create a background image
image = Image.new('RGB', (300, 50), (220,210,190))
draw = ImageDraw.Draw(image)

# Create a text image
textImg = Image.new('RGB',(150,40),(0,0,0))
tmpDraw = ImageDraw.Draw(textImg)
textFont = ImageFont.truetype('ARIAL.TTF',36)
tmpDraw.text((0, 0), 'Hello', font = textFont, fill = (10,200,200))
textImg = textImg.rotate(-10)

# Create a mask (same size as the text image)
mask = Image.new('L',(150, 40),0) 
mask.paste(textImg,(0,0))

# Paste text image with the mask
image.paste(textImg,(100,0),mask)

image.save('hello.jpg')


In order to generate CAPTCHA-like image, you might want to apply random xy, color, font size, lines, etc...

So it'll be like this:

captcha.jpg

This is entire source for these examples. Please install PIL (do easy_install PIL) first.


Download Source Code Here (7.95KB)



Labels:


posted by Kiichi Takeuchi at 1:44 PM

0 Comments:

Post a Comment

<< Home