- python验证码图片类,返回png图片和验证码字符串并且下载字体文件
- 记得安装PIL库和下载字体文件
- 用于登录注册验证码
import random
import string
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from io import BytesIO
class ValidCodeImg():
def __init__(self,width=120,height=50,code_count=4,font_size=32,point_count=20,line_count=3,img_type='png'):
'''
生成验证码
:param width: 宽度
:param height: 高度
:param code_count: 验证码数量
:param font_size: 字体大小
:param point_count: 噪点个数
:param line_count: 划线个数
:param img_type: 图片类型
'''
self.width = width
self.height = height
self.code_count = code_count
self.font_size = font_size
self.point_count = point_count
self.line_count = line_count
self.img_type = img_type
@staticmethod
def getRandomColor():
'''
获取随即颜色
:return: RGB() 元组
'''
red = random.randint(0,255)
green = random.randint(0,255)
blue = random.randint(0,255)
return (red,green,blue)
@staticmethod
def getRandomStr():
'''
获取0-9 a-z A-Z的随机1个字符
:return:string
'''
return ''.join(random.sample(string.ascii_letters + string.digits, 1))
def getValidCodeImg(self):
#生成一个150*30的随即颜色图片
image = Image.new('RGB',(self.width,self.height),self.getRandomColor())
#画笔
draw = ImageDraw.Draw(image)
#字体 C:\Windows\Fonts
font = ImageFont.truetype('App/static/Font/Inkfree.ttf',size=self.font_size)
#验证码
List = []
for i in range(self.code_count):
randomStr = self.getRandomStr()
#写入验证码
draw.text((10+i*30,-2),randomStr,self.getRandomColor(),font=font)
List.append(randomStr)
valid_str = ''.join(List)
#噪线
for i in range(self.line_count):
x1 = random.randint(0,self.width)
x2 = random.randint(0,self.width)
y1 = random.randint(0,self.height)
y2 = random.randint(0,self.height)
draw.line((x1,y1,x2,y2),fill=self.getRandomColor())
#噪点
for i in range(self.point_count):
#点
draw.point([random.randint(0,self.width),random.randint(0,self.height)],fill=self.getRandomColor())
x = random.randint(0,self.width)
y = random.randint(0,self.height)
draw.arc((x,y,x+4,y+4),0,90,fill=self.getRandomColor())
#保存图片
f = BytesIO()
image.save(f,self.img_type)
data = f.getvalue()
f.close()
return data,valid_str
if __name__ == '__main__':
str = ValidCodeImg.getRandomStr()
print(str)