import os
from random import randint, sample
from PIL import ImageFont, Image, ImageDraw
from io import BytesIO
# 驗證碼類
# from Bloger import settings
class VerfiyCode:
def __init__(self,width=100,height=40,len=4):
"""
系統初始化
:param width: 驗證碼圖片寬度
:param height: 驗證碼圖片高度
:param len: 驗證碼長度
"""
self.width = width if width > 50 else 100
self.height = height if height > 30 else 40
self.len = len if len >= 4 else 4
self._code = '' #驗證碼字符串
self.__pen = None #畫筆
@property
def code(self):
return self._code
def output(self):
"""
輸出驗證碼
:return: 驗證碼圖片的二進制流
"""
# 1 創建畫布
im = Image.new('RGB',(self.width,self.height),self.__randColor(120,200))
self.__pen = ImageDraw.Draw(im) #產生畫筆
# 2 產生驗證碼字符串
self.generateCode()
# print(self._code)
# 3 畫驗證碼
self.__drawCode()
# 4. 畫干擾點
self.__drawpoint()
# 5 畫干擾線
self.__drawline()
# 6 返回圖片
#保存圖片
im.save(r'G:\項目_準備\數據分析項目\個人分析\rent_home\home\static\img\vc.png','PNG')
#將圖片轉化爲二進制流返回
buf = BytesIO()
im.save(buf,'png')
res = buf.getvalue()
buf.close()
return res
def __randColor(self,low,high):
return randint(low,high),randint(low,high),randint(low,high)
def generateCode(self):
"""
產生純數字驗證碼
:return: 無
"""
num = ''
for i in range(self.len):
num += str(randint(0,9))
self._code = num
def __drawCode(self):
"""
畫驗證碼
:return:
"""
path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'/static/fonts/STHUPO.TTF')
# print(path)
font1 = ImageFont.truetype(path,size=20,encoding='utf-8')
# print(font1)
# 一個字符寬度
width = (self.width - 20)/self.len
for i in range(self.len):
x = 10 + i * width + width / 4
y = randint(5,self.height-25)
self.__pen.text((x,y),self._code[i],font=font1,fill=self.__randColor(0,100))
def __drawpoint(self):
for i in range(300):
x = randint(1,self.width - 1)
y = randint(1,self.height - 1)
self.__pen.point((x,y),fill=self.__randColor(60,160))
def __drawline(self):
# print(self._code)
for i in range(6):
# 起點座標
start = (randint(1,self.width - 1),randint(1,self.height - 1))
end = (randint(1,self.width - 1),randint(1,self.height - 1))
self.__pen.line([start,end],fill=self.__randColor(120,200))
#該類可以自定義驗證碼字符串,使該類繼承上邊畫驗證碼VerfiyCode類。
# class StrCode(VerfiyCode):
# def generateCode(self):
#讓驗證碼顯示爲s1中的字母形式,s1你可以隨意定義。
# s1 = 'QWERTYUPASDFGHJKLZXCVBNMqwertyupasdfghjklzxcvbnm'
# res = sample(s1,self.len)
# res = ''.join(res)
# print(res)
# self._code = res
# if __name__ == "__main__":
# vc = VerfiyCode()
# print(vc.output())
# print(vc.code)
django flask框架web開發使用驗證碼
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.