验证码生成

Posted yanhuazidi

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了验证码生成相关的知识,希望对你有一定的参考价值。

 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)

 

以上是关于验证码生成的主要内容,如果未能解决你的问题,请参考以下文章

JavaScript 有用的代码片段和 trick

验证码识别与生成类API调用的代码示例合集:六位图片验证码生成四位图片验证码生成简单验证码识别等

代码实现PHP生成各种随机验证码

JAVA生成验证码代码

随机验证码生成代码 (转)

thinkphp3.2验证码怎么写