码迷,mamicode.com
首页 > 其他好文 > 详细

验证码生成

时间:2019-01-30 12:59:47      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:style   生成   rom   ext   verify   ane   http   value   first   

 1 from django.http import HttpResponse
 2 from PIL import Image, ImageDraw, ImageFont
 3 import random
 4 
 5 def rmdRGB():
 6     C1 = random.randrange(0,255)
 7     C2 = random.randrange(10,255)
 8     C3 =random.randrange(60,255)
 9     return (C1,C2,C3)
10 
11 def verifycode(request):
12     # 背景色,长度,宽度
13     # bgcolor = ‘#997679‘
14     bgcolor = #FFFFFF
15     width = 100
16     height = 25
17     # 创建画布
18     im = Image.new(RGB,(width,height),bgcolor)
19     # 创建画笔
20     draw = ImageDraw.Draw(im)
21     # 画点
22     for i in range(0, 100):
23         xy=(random.randrange(0,width),random.randrange(0,height))
24         fill=(random.randrange(0,255),255,random.randrange(0,255))
25         draw.point(xy,fill=fill)
26 
27     # 添加文字
28     # str1 = ‘ABCD123DEFGHIJK456LMNOPQRS789TUVWXYZ0‘
29     # rand_str = ‘‘
30     # for i in range(0,4):
31     #     rand_str += str1[random.randrange(0,len(str1))]
32     font = ImageFont.truetype(/usr/share/fonts/truetype/fonts-japanese-gothic.ttf,23)
33     # draw.text((5,2),rand_str,fill=rmdRGB(),font=font)
34 
35     numb_1 = {"1":"","2":"","3":"","4":"","5":"","6":"","7":"","8":"","9":"",}
36     numb_2 = random.randint(1,50)
37     sign = ["+","-"]
38     numb_1_n = random.randrange(1,10)
39     numb_1_s = str(numb_1_n)
40     first_s = numb_1[numb_1_s]
41     third_s = str(numb_2)
42     sign_n = random.randrange(0,2)
43     second_s = sign[sign_n]
44     if sign_n == 0:
45         last = numb_1_n +numb_2
46     else:
47         last = numb_2 - numb_1_n
48     last_s = str(last)
49     draw.text((5,2),?,font=font,fill=rmdRGB())
50     draw.text((20,2),second_s,font=font,fill=rmdRGB())
51     draw.text((35,2),first_s,font=font,fill=rmdRGB())
52     draw.text((60,2),=,font=font,fill=rmdRGB())
53     draw.text((75,2),last_s,font=font,fill=rmdRGB())
54 
55     # 添加干扰线
56     for i in range(5):
57         x1 = random.randrange(0,width)
58         y1 = random.randrange(0,height)
59         x2 = random.randrange(0,width)
60         y2 = random.randrange(0, height)
61         draw.line((x1,y1,x2,y2),fill=rmdRGB())
62 
63     # 添加圆
64     for i in range(40):
65         x = random.randrange(0, width)
66         y = random.randrange(0, height)
67         draw.arc((x,y,x+4,y+4),0,90,fill=rmdRGB())
68 
69     # 结束
70     del draw
71     import io
72     buf = io.BytesIO()
73     im.save(buf,png)
74     return HttpResponse(buf.getvalue(),image/png)

 

验证码生成

标签:style   生成   rom   ext   verify   ane   http   value   first   

原文地址:https://www.cnblogs.com/yanhuazidi/p/10337373.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!