Python生成随机验证码,需要使用PIL模块.
安装:
pip3 install pillow
1
1
pip3 install pillow
基本使用
1.创建图片
from PIL import Image #导入模块
img=Image.new(mode="RGB",size=(120,40),color="yellow")
f=open("validCode.png","wb")
img.save(f,"png")
with open("validCode.png","rb") as f:
data=f.read()
return HttpResponse(data)
7
1
from PIL import Image #导入模块
2
img=Image.new(mode="RGB",size=(120,40),color="yellow")
3
f=open("validCode.png","wb")
4
img.save(f,"png")
5
with open("validCode.png","rb") as f:
6
data=f.read()
7
return HttpResponse(data)
2. 创建画笔,用于在图片上画任意内容
img = Image.new(mode='RGB', size=(120, 30), color=(255, 255, 255))
1
1
img = Image.new(mode='RGB', size=(120, 30), color=(255, 255, 255))
3.画点
img=Image.new(mode="RGB",size=(120,40),color="yellow")
draw=ImageDraw.Draw(img,mode='RGB')
draw.point([100,100],fill=255,255,255)
#第一个参数:表示坐标
#第二个参数:表示颜色
5
1
img=Image.new(mode="RGB",size=(120,40),color="yellow")
2
draw=ImageDraw.Draw(img,mode='RGB')
3
draw.point([100,100],fill=255,255,255)
4
#第一个参数:表示坐标
5
#第二个参数:表示颜色
4.画线
draw.line((100,100,300,100), fill=(255, 255, 255))
#第一个表示起始坐标和结束坐标
#第二个参数:表示颜色
3
1
draw.line((100,100,300,100), fill=(255, 255, 255))
2
#第一个表示起始坐标和结束坐标
3
#第二个参数:表示颜色
5. 画圆
img = Image.new(mode='RGB', size=(120, 30), color=(255, 255, 255))
draw = ImageDraw.Draw(img, mode='RGB')
draw.arc((100,100,300,300),0,90,fill="red")
# 第一个参数:表示起始坐标和结束坐标(圆要画在其中间)
# 第二个参数:表示开始角度
# 第三个参数:表示结束角度
# 第四个参数:表示颜色
8
1
img = Image.new(mode='RGB', size=(120, 30), color=(255, 255, 255))
2
draw = ImageDraw.Draw(img, mode='RGB')
3
4
draw.arc((100,100,300,300),0,90,fill="red")
5
# 第一个参数:表示起始坐标和结束坐标(圆要画在其中间)
6
# 第二个参数:表示开始角度
7
# 第三个参数:表示结束角度
8
# 第四个参数:表示颜色
6. 写文本 text
draw.text([0,0],'python',"red")
# 第一个参数:表示起始坐标
# 第二个参数:表示写入内容
# 第三个参数:表示颜色
4
1
draw.text([0,0],'python',"red")
2
# 第一个参数:表示起始坐标
3
# 第二个参数:表示写入内容
4
# 第三个参数:表示颜色
1
1
验证码的几种使用方式
#方式一
#通过静态文件的目录来定位路径
import os
path = os.path.join(settings.BASE_DIR,"static","img","ss.jpg") #BASE_DIR表示settings的上一级目录的上一级目录
with open(path,"rb") as f:
data=f.read()
#方式二
from PIL import Image #导入PIL模块
img=Image.new(mode="RGB",size=(120,40),color="yellow") #创建画笔
f=open("validCode.png","wb") #保存在本地
img.save(f,"png")
with open("validCode.png","rb") as f: #进行读取
data=f.read()
return HttpResponse(data) #然后返回给前端
'''
缺点:
会在服务端的根目录下产生一个文件,我们不应该让它产生文件
'''
#方式三
'''
把文件读到内存中去
'''
from io import BytesIO
from PIL import Image
img=Image.new(mode="RGB",size=(120,40),color="blue")
f=BytesIO()
img.save(f,"png")
data=f.getvalue()
return HttpResponse(data)
#方式四
'''
随机产生验证码
'''
# def text(self, xy, text, fill=None, font=None, anchor=None,*args, **kwargs):
from io import BytesIO #把内容保存到内存中
import random
from PIL import Image,ImageDraw,ImageFont #导入图画,画笔,字体
img = Image.new(mode="RGB", size=(120, 40), color=(random.randint(0,255),random.randint(0,255),random.randint(0,255)))
draw=ImageDraw.Draw(img,"RGB")
font=ImageFont.truetype("blog/static/font/kumo.ttf",25)
def fandomColor():
'''
生成随机颜色
:return:
'''
random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)
valid_list=[]
for i in range(5):
random_num=str(random.randint(0,9))
random_lower_zimu=chr(random.randint(65,90))
random_upper_zimu=chr(random.randint(97,122))
random_char=random.choice([random_num,random_lower_zimu,random_upper_zimu])
draw.text([5+i*24,10],random_char,(fandomColor()),font=font)
valid_list.append(random_char)
for i in range(100):
draw.point([random.randint(0, 5+i*24), random.randint(0,5+i*24 )], fill=fandomColor())
f=BytesIO()
img.save(f,"png")
data=f.getvalue()
valid_str="".join(valid_list)
print(valid_str)
request.session["keepValidCode"]=valid_str
return HttpResponse(data)
x
1
#方式一
2
#通过静态文件的目录来定位路径
3
import os
4
path = os.path.join(settings.BASE_DIR,"static","img","ss.jpg") #BASE_DIR表示settings的上一级目录的上一级目录
5
with open(path,"rb") as f:
6
data=f.read()
7
8
9
10
#方式二
11
from PIL import Image #导入PIL模块
12
img=Image.new(mode="RGB",size=(120,40),color="yellow") #创建画笔
13
f=open("validCode.png","wb") #保存在本地
14
img.save(f,"png")
15
with open("validCode.png","rb") as f: #进行读取
16
data=f.read()
17
return HttpResponse(data) #然后返回给前端
18
'''
19
缺点:
20
会在服务端的根目录下产生一个文件,我们不应该让它产生文件
21
'''
22
#方式三
23
'''
24
把文件读到内存中去
25
'''
26
from io import BytesIO
27
from PIL import Image
28
img=Image.new(mode="RGB",size=(120,40),color="blue")
29
f=BytesIO()
30
img.save(f,"png")
31
data=f.getvalue()
32
return HttpResponse(data)
33
34
35
36
#方式四
37
'''
38
随机产生验证码
39
'''
40
# def text(self, xy, text, fill=None, font=None, anchor=None,*args, **kwargs):
41
42
from io import BytesIO #把内容保存到内存中
43
import random
44
45
from PIL import Image,ImageDraw,ImageFont #导入图画,画笔,字体
46
img = Image.new(mode="RGB", size=(120, 40), color=(random.randint(0,255),random.randint(0,255),random.randint(0,255)))
47
48
draw=ImageDraw.Draw(img,"RGB")
49
font=ImageFont.truetype("blog/static/font/kumo.ttf",25)
50
def fandomColor():
51
'''
52
生成随机颜色
53
:return:
54
'''
55
random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)
56
valid_list=[]
57
for i in range(5):
58
59
random_num=str(random.randint(0,9))
60
random_lower_zimu=chr(random.randint(65,90))
61
random_upper_zimu=chr(random.randint(97,122))
62
63
random_char=random.choice([random_num,random_lower_zimu,random_upper_zimu])
64
draw.text([5+i*24,10],random_char,(fandomColor()),font=font)
65
valid_list.append(random_char)
66
67
for i in range(100):
68
draw.point([random.randint(0, 5+i*24), random.randint(0,5+i*24 )], fill=fandomColor())
69
f=BytesIO()
70
img.save(f,"png")
71
data=f.getvalue()
72
73
valid_str="".join(valid_list)
74
print(valid_str)
75
76
request.session["keepValidCode"]=valid_str
77
78
return HttpResponse(data)
79
80
81
82
83
验证码的局部刷新
当有时验证码看不太清时,需要进行验证码的刷新,可以在img中src的路径中加上1个>相当于对服务器发起一次请求
示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="/static/bootstrap-3.3.7/css/bootstrap.min.css">
<script src="/static/jquery-3.2.1.js"></script>
<script src="/static/bootstrap-3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<form class="form-horizontal">
{% csrf_token %}
<div class="form-group">
<label for="username" class="col-sm-2 control-label">用户名</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="username" placeholder="用户名">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">Password</label>
<div class="col-sm-4">
<input type="password" class="form-control" id="password" placeholder="Password">
</div>
</div>
<div class="form-group">
<label for="validCode" class="col-sm-2 control-label">验证码</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="validCode" placeholder="验证码">
<img src="/get_verification_img/" alt="" class="valid_code_img" >
<a class="refresh">刷新</a>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default signlogin">Sign in</button>
</div>
<div class="col-sm-offset-2 col-sm-10">
</div>
</div>
</form>
<script>
$(".refresh").click(function () {
$(".valid_code_img")[0].src+="?";
});
$("img").click(function () {
$(this)[0].src+="?";
});
</script>
x
50
1
<!DOCTYPE html>
2
<html lang="en">
3
<head>
4
<meta charset="UTF-8">
5
<title>Title</title>
6
<link rel="stylesheet" href="/static/bootstrap-3.3.7/css/bootstrap.min.css">
7
<script src="/static/jquery-3.2.1.js"></script>
8
<script src="/static/bootstrap-3.3.7/js/bootstrap.min.js"></script>
9
</head>
10
<body>
11
<form class="form-horizontal">
12
{% csrf_token %}
13
<div class="form-group">
14
<label for="username" class="col-sm-2 control-label">用户名</label>
15
<div class="col-sm-4">
16
<input type="text" class="form-control" id="username" placeholder="用户名">
17
</div>
18
</div>
19
<div class="form-group">
20
<label for="inputPassword3" class="col-sm-2 control-label">Password</label>
21
<div class="col-sm-4">
22
<input type="password" class="form-control" id="password" placeholder="Password">
23
</div>
24
</div>
25
<div class="form-group">
26
<label for="validCode" class="col-sm-2 control-label">验证码</label>
27
<div class="col-sm-4">
28
<input type="text" class="form-control" id="validCode" placeholder="验证码">
29
<img src="/get_verification_img/" alt="" class="valid_code_img" >
30
<a class="refresh">刷新</a>
31
</div>
32
</div>
33
<div class="form-group">
34
<div class="col-sm-offset-2 col-sm-10">
35
<button type="submit" class="btn btn-default signlogin">Sign in</button>
36
</div>
37
<div class="col-sm-offset-2 col-sm-10">
38
39
</div>
40
</div>
41
42
</form>
43
44
<script>
45
$(".refresh").click(function () {
46
$(".valid_code_img")[0].src+="?";
47
});
48
$("img").click(function () {
49
$(this)[0].src+="?";
50
});
51
</script>