文章連接: https://mp.weixin.qq.com/s/LYUBRNallHcjnhJb1R3ZBg
平常在網站使用過程當中常常遇到圖形驗證,今天準備本身作個圖形驗證碼,這算是個簡單的功能,也適合新手練習的,便於本身學習。
主要用到的庫--PIL圖像處理庫,簡單的思路,咱們須要隨機的顏色,隨機的數字或字母,隨機的線條、點做爲干擾元素 拼湊成一張圖片。 前端
生成隨機顏色,返回的是rgb三色。微信
def getRandomColor(): r = random.randint(0, 255) g = random.randint(0, 255) b = random.randint(0, 255) return (r, g, b)
從數字、大小寫字母裏生成隨機字符。dom
def getRandomChar(): random_num = str(random.randint(0, 9)) random_lower = chr(random.randint(97, 122)) # 小寫字母a~z random_upper = chr(random.randint(65, 90)) # 大寫字母A~Z random_char = random.choice([random_num, random_lower, random_upper]) return random_char
圖片操做,生成一張隨機背景色的圖片,隨機生成5種字符+5種顏色,在圖片上描繪字,因爲默認的字體很小,還須要對字進行處理,不一樣系統下的字體文件存放位置不同,這裏我是把window下的 arial.ttf 字體複製到了當前文件夾下直接使用的。學習
# 圖片寬高 width = 160 height = 50 def createImg(): bg_color = getRandomColor() # 建立一張隨機背景色的圖片 img = Image.new(mode="RGB", size=(width, height), color=bg_color) # 獲取圖片畫筆,用於描繪字 draw = ImageDraw.Draw(img) # 修改字體 font = ImageFont.truetype(font="arial.ttf", size=36) for i in range(5): # 隨機生成5種字符+5種顏色 random_txt = getRandomChar() txt_color = getRandomColor() # 避免文字顏色和背景色一致重合 while txt_color == bg_color: txt_color = getRandomColor() # 根據座標填充文字 draw.text((10 + 30 * i, 3), text=random_txt, fill=txt_color, font=font) # 打開圖片操做,並保存在當前文件夾下 with open("test.png", "wb") as f: img.save(f, format="png")
這個時候能夠看到文件夾下面的圖片 字體
這裏是張很清晰的圖片,爲了有干擾元素,這裏還須要在圖片加入些線條、點做爲干擾點。
隨機畫線,在圖片寬高範圍內隨機生成2個座標點,並經過隨機顏色產生線條。網站
def drawLine(draw): for i in range(5): x1 = random.randint(0, width) x2 = random.randint(0, width) y1 = random.randint(0, height) y2 = random.randint(0, height) draw.line((x1, y1, x2, y2), fill=getRandomColor())
隨機畫點,隨機生成橫縱座標點。url
def drawPoint(draw): for i in range(50): x = random.randint(0, width) y = random.randint(0, height) draw.point((x,y), fill=getRandomColor())
生成方法spa
def createImg(): bg_color = getRandomColor() # 建立一張隨機背景色的圖片 img = Image.new(mode="RGB", size=(width, height), color=bg_color) # 獲取圖片畫筆,用於描繪字 draw = ImageDraw.Draw(img) # 修改字體 font = ImageFont.truetype(font="arial.ttf", size=36) for i in range(5): # 隨機生成5種字符+5種顏色 random_txt = getRandomChar() txt_color = getRandomColor() # 避免文字顏色和背景色一致重合 while txt_color == bg_color: txt_color = getRandomColor() # 根據座標填充文字 draw.text((10 + 30 * i, 3), text=random_txt, fill=txt_color, font=font) # 畫干擾線點 drawLine(draw) drawPoint(draw) # 打開圖片操做,並保存在當前文件夾下 with open("test.png", "wb") as f: img.save(f, format="png")
最終生成的圖片
這裏介紹的是圖片生成的方法,能夠將圖片直接顯示在前端,也可使用接口返回url。這裏我簡單的把圖片作成連接顯示在網頁上,https://www.manjiexiang.cn/blog/validate 用Django作的,須要注意的是圖片保存的路徑。 code
歡迎關注個人我的博客:https://www.manjiexiang.cn/ orm
更多精彩歡迎關注微信號:春風十里不如認識你
一塊兒學習,一塊兒進步,歡迎上車,有問題隨時聯繫,一塊兒解決!!!