python應用學習(二)——生成驗證碼
阿新 • • 發佈:2021-02-10
python應用學習(二)——生成驗證碼
前言
網站為例防止惡意註冊、發帖等惡意操作而設定了驗證碼,其原理是將一串隨機產生的數字或字母生成一幅圖片,圖片上加一下干擾元素。本文介紹利用python生成一個驗證碼,其中程式碼做了註釋並於相關知識的解答
完成目標:
生成如圖所示的驗證碼
一、準備
1、python環境
2、涉及到的python庫需要 pip install 包名
安裝
pip install pillow
二、程式碼編寫
1.引入庫
import random,string,sys,math
from PIL import Image,ImageDraw,ImageFont,ImageFilter
import os
2.配置初始化引數
font_path = 'C:\Windows\Fonts\simfang.ttf' #字型位置
number = 5 #生成幾位數的驗證碼
size =(100,40) #生成驗證碼的影象大小
bgcolor = (255,255 ,255) #生成的背景色(白色)
draw_line = True #是否要加干擾線和干擾點
path = "vertification.png" #驗證碼存放位置
3.生成隨機字串
def random_text ():
source = list(string.ascii_letters)
#print(source)
for index in range(0,10):
source.append (str(index))
return ''.join(random.sample(source,1))
4.生成干擾線和干擾點
def random_line(drawpen,width,height):
for i in range(random.randint(4,8)):
linecolor = (random.randint(0,255),random.randint(0,255),random.randint(0,255)) #干擾線的顏色隨機
begin = (random.randint(0,width),random.randint(0,height)) #干擾線的位置隨機
end = (random.randint(0,width),random.randint(0,height))
drawpen.line([begin,end],fill = linecolor)
def random_point(drawpen,width,height):
for i in range(20):
linecolor = (random.randint(0,255),random.randint(0,255),random.randint(0,255)) #干擾點的顏色隨機
begin = (random.randint(0,width),random.randint(0,height)) #干擾點的位置隨機
end = (random.randint(0,width),random.randint(0,height))
drawpen.point([begin,end],fill = linecolor)
5.生成驗證碼的函式
def get_code():
x_start = 2
y_start = 0
width,height = size #驗證碼的寬和高
image = Image.new('RGBA',(width,height),bgcolor) #建立圖片
font = ImageFont.truetype(font_path,25) #設定驗證碼的字型
drawpen = ImageDraw.Draw(image) #生成畫筆
for i in range(number):
fontcolor = (random.randint(0,255),random.randint(0,255),random.randint(0,255)) #驗證碼字型的顏色隨機
text = random_text()
#font_width,font_height = font.getsize(text)
x = x_start + i * int(width / (number))
y = random.randint(y_start, int(height / 2))
drawpen.text((x, y), text = text,font = font,fill = fontcolor)
# drawpen.text(((width - font_width) / number,(height - font_height) / number),text = text,font = font,fill = fontcolor)
if draw_line:
random_line(drawpen,width,height)
random_point(drawpen,width,height)
# image = image.transform((width + 20,height + 20),Image.AFFINE,(1,-0.3,0,-0.1,1,0),Image.BILINEAR) #建立扭曲
# image = image.filter(ImageFilter.EDGE_ENHANCE_MORE) #扭曲,邊界加強
image.save(path)
os.startfile(path)
6.呼叫
if __name__ == "__main__":
get_code()
最後
完整程式碼:(有後續補充的 詳細註釋)
https://download.csdn.net/download/weixin_45386875/15158218
其他python應用例項見:https://blog.csdn.net/weixin_45386875/article/details/113766276