- 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: 驗證碼數(shù)量
:param font_size: 字體大小
:param point_count: 噪點個數(shù)
:param line_count: 劃線個數(shù)
: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的隨機(jī)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)