1 view.py
2
3 from utils.image_code import check_code
4 from io import BytesIO
5 # 验证码图片生成
6 def GetCode(request):
7 image_object, code = check_code()
8 # 存放验证码code
9 request.session['img_code'] = code
10 # 设置过期时间
11 request.session.set_expiry(180)
12 stream = BytesIO()
13 image_object.save(stream, 'png')
14 return HttpResponse(stream.getvalue())
15
16 urls.py
17 # 验证码图片生成
18 url(r'^code/$', account.GetCode, name='code'),
19 # check_code.py
20
22 from PIL import Image, ImageDraw, ImageFont, ImageFilter
23 import random
24
25
26 def check_code(width=120, height=30, char_length=5, font_file='Monaco.ttf', font_size=28):
27 code = []
28 img = Image.new(mode='RGB', size=(width, height), color=(255, 255, 255))
29 draw = ImageDraw.Draw(img, mode='RGB')
30
31 def rndChar():
32 """
33 生成随机字母
34 :return:
35 """
36 return chr(random.randint(65, 90))
37
38 def rndColor():
39 """
40 生成随机颜色
41 :return:
42 """
43 return (random.randint(0, 255), random.randint(10, 255), random.randint(64, 255))
44
45 # 写文字
46 font = ImageFont.truetype(font_file, font_size)
47 for i in range(char_length):
48 char = rndChar()
49 code.append(char)
50 h = random.randint(0, 4)
51 draw.text([i * width / char_length, h], char, font=font, fill=rndColor())
52
53 # 写干扰点
54 for i in range(40):
55 draw.point([random.randint(0, width), random.randint(0, height)], fill=rndColor())
56
57 # 写干扰圆圈
58 for i in range(40):
59 draw.point([random.randint(0, width), random.randint(0, height)], fill=rndColor())
60 x = random.randint(0, widtha)
61 y = random.randint(0, height)
62 draw.arc((x, y, x + 4, y + 4), 0, 90, fill=rndColor())
63
64 # 画干扰线
65 for i in range(5):
66 x1 = random.randint(0, width)
67 y1 = random.randint(0, height)
68 x2 = random.randint(0, width)
69 y2 = random.randint(0, height)
70
71 draw.line((x1, y1, x2, y2), fill=rndColor())
72
73 img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)
74 return img, ''.join(code)
75
76
77 if __name__ == '__main__':
78 image_object, code = check_code()
79
80 # 把图片写入文件
81 """
82 with open('code.png', 'wb') as f:
83 image_object.save(f, format='png')
84 """
85
86 # 把图片的内容写到内存 stream
87 """
88 from io import BytesIO
89 stream = BytesIO()
90 image_object.save(stream, 'png')
91 stream.getvalue()
92 """