python PIL 生成图片验证码

下面是一个用python PIL 生成验证码的函数。

python PIL 生成图片验证码

过程是:创建一张有底色的图片、在背景上添加杂色、写上特定文字、保存图片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# -*- coding: utf-8 -*-

import random
import Image
import ImageFont
import ImageDraw
import ImageFilter


def gen_captcha(text, fnt, fnt_sz, file_name, fmt='JPEG'):
    # 随机生成背景色
    fgcolor = random.randint(0,0xffff00)
    bgcolor = fgcolor ^ 0xffffff

    # 生成文字
    font = ImageFont.truetype(fnt,fnt_sz)
    dim = font.getsize(text)
    
    im = Image.new('RGB', (dim[0]+5,dim[1]+5), bgcolor)
    d = ImageDraw.Draw(im)
    x, y = im.size
    r = random.randint

    # 给背景添加杂色
    for num in range(100):
        d.rectangle((r(0,x), r(0,y), r(0,x), r(0,y)), fill=r(0, 0xffffff))
    
    # 添加文字
    d.text((3,3), text, font=font, fill=fgcolor)
    im = im.filter(ImageFilter.EDGE_ENHANCE_MORE)
    
    im.save(file_name, format=fmt)


def gen_random_word(wordLen=6):
    allowedChars = "abcdefghijklmnopqrstuvwzyzABCDEFGHIJKLMNOPQRSTUVWZYZ0123456789"
    word = ""
    for i in range(0, wordLen):
        word = word + allowedChars[random.randint(0,0xffffff) % len(allowedChars)]
    return word

if __name__ == '__main__':
    word = gen_random_word()
    print word
    gen_captcha(word.strip(), 'porkys.ttf', 65, "test.jpg")

进阶使用

一般情况不会要求填写验证码,避免影响用户体验。在特定情况下,如当用户登录密码出错N 次后,当用户频繁发贴时。

可对验证码作更复杂的变换,当用户输入验证码出错次数为N 时,增加其难度,如增加字符集、变化字体等。

本文网址: https://pylist.com/topic/99.html 转摘请注明来源

Suggested Topics

python 对中文链接安全转码

当一个链接里包含中文时,有些浏览器并不能正确解析,这就需要首先对中文作安全转码,这里介绍用 python 对中文链接安全转码,...

python 高效的list 去重方式

list 去重是编程中经常用到的,python 的去重方式很灵活,下面介绍多种去重方式,并比较得出最高效的方式。...

Leave a Comment