web/captcha.py
branch3.22
changeset 11405 5ba55f4c813a
parent 10609 e2d8e81bfe68
parent 11399 5149a4d4cf54
child 11431 bc473cddba5e
equal deleted inserted replaced
11392:12bebe48b451 11405:5ba55f4c813a
    39     """Generate a captcha image. Return a PIL image object.
    39     """Generate a captcha image. Return a PIL image object.
    40 
    40 
    41     adapted from http://code.activestate.com/recipes/440588/
    41     adapted from http://code.activestate.com/recipes/440588/
    42     """
    42     """
    43     # randomly select the foreground color
    43     # randomly select the foreground color
    44     fgcolor = randint(0, 0xffff00)
    44     fgcolor = (randint(100, 256), randint(100, 256), randint(100, 256))
    45     # make the background color the opposite of fgcolor
       
    46     bgcolor = fgcolor ^ 0xffffff
       
    47     # create a font object
    45     # create a font object
    48     font = ImageFont.truetype(fontfile, fontsize)
    46     font = ImageFont.truetype(fontfile, fontsize)
    49     # determine dimensions of the text
    47     # determine dimensions of the text
    50     dim = font.getsize(text)
    48     dim = font.getsize(text)
    51     # create a new image slightly larger that the text
    49     # create a new image slightly larger that the text
    52     img = Image.new('RGB', (dim[0]+5, dim[1]+5), bgcolor)
    50     img = Image.new('RGB', (dim[0]+15, dim[1]+5), 0)
    53     draw = ImageDraw.Draw(img)
    51     draw = ImageDraw.Draw(img)
    54     # draw 100 random colored boxes on the background
    52     # draw 100 random colored boxes on the background
    55     x, y = img.size
    53     x, y = img.size
    56     for num in range(100):
    54     for num in range(100):
       
    55     for num in xrange(100):
       
    56         fill = (randint(0, 100), randint(0, 100), randint(0, 100))
    57         draw.rectangle((randint(0, x), randint(0, y),
    57         draw.rectangle((randint(0, x), randint(0, y),
    58                         randint(0, x), randint(0, y)),
    58                         randint(0, x), randint(0, y)),
    59                        fill=randint(0, 0xffffff))
    59                        fill=fill)
    60     # add the text to the image
    60     # add the text to the image
    61     draw.text((3, 3), text, font=font, fill=fgcolor)
    61     # we add a trailing space to prevent the last char to be truncated
       
    62     draw.text((3, 3), text + ' ', font=font, fill=fgcolor)
    62     img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)
    63     img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)
    63     return img
    64     return img
    64 
    65 
    65 
    66 
    66 def captcha(fontfile, fontsize, size=5, format='JPEG'):
    67 def captcha(fontfile, fontsize, size=5, format='JPEG'):