模擬動態產生驗證碼圖片
模擬生成驗證碼,首先要做的是生成隨機的字母,然后對字母進行模糊處理。這里介紹一下 Python 提供的 Pillow 模塊。
Pillow
PIL:Python Image Library,Python 的圖像處理標準庫,功能強大。
PIL 是第三方庫,使用之前需要先進行安裝。具體的命令如下:(如果安裝了 Anaconda,這一步可以跳過)
$ pip install pillow
下面先簡單介紹 Pillow 的功能。
操作圖像
縮放圖像,是 Pillow 的一個功能,示例如下:
from PIL import Image# 打開圖片,注意路徑img = Image.open('pitbull.jpeg')# 獲得圖片尺寸weight, height = img.sizeprint('原圖片尺寸:{}x{}'.format(weight, height))# 進行縮放,縮放 50%img.thumbnail((weight//2, height//2))print('調整后的圖片尺寸:{}x{}'.format(weight//2, height//2))# 將縮放后的圖片保存img.save('thumbnail.jpg', 'jpeg')
Pillow 還有其他的功能,例如旋轉,剪切,濾鏡,輸出文字,調色板等。
ImageFilter
下面嘗試模糊圖片處理:
from PIL import Image,ImageFilter# 打開圖片文件,注意路徑img = Image.open('pitbull.jpeg')# 應用模糊濾鏡img2 = img.filter(ImageFilter.BLUR)img2.save('blur.jpg', 'jpeg')
ImageFilter 是 Python 提供的圖像濾波,而 ImageFilter.BLUR 是模糊濾波。
上面代碼具體的效果如下:
ImageDraw
同時 Pillow 的 ImageDraw 提供了一些列繪圖方法,使我們可以直接繪圖。下面使用這種方法來嘗試生成字母驗證碼圖片:
# -*- coding: utf-8 -*-'''@File: generate_random_code.py@Time: 2020/01/31 20:32:10@Author: 大夢三千秋@Contact: yiluolion@126.com'''# Put the import lib herefrom random import randint, choicefrom PIL import Image, ImageDraw, ImageFont, ImageFilterdef rnd_chr(chr_set): '''獲取隨機字符 Args: chr_set: 擬定生成的字符集 Returns: 返回隨機字符 ''' return choice(chr_set)def rnd_bg_color(): '''獲取隨機像素值,填充背景 Returns: 返回隨機像素值,返回元組類型 ''' return (randint(97, 255), randint(97, 255), randint(97, 255))def rnd_chr_color(): '''獲取隨機像素,填充輸出字符 Returns: 返回隨機像素值,返回元組類型 ''' # 與畫板填充色進行一定的錯開,防止完全覆蓋 return (randint(32, 96), randint(32, 96), randint(32, 96))def main(): # 生成字符集 chr_set = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] for i in range(65, 91): chr_set.append(chr(i)) for j in range(97, 123): chr_set.append(chr(j)) # print(chr_set) # 定義畫板規格 250 x 50 width = 60 * 5 height = 60 # 創建 Image 對象,白底畫板 image = Image.new('RGB', (width, height), (255, 255, 255)) # 創建 Draw 對象 draw = ImageDraw.Draw(image) # 創建 Font 對象 font = ImageFont.truetype('./consola.ttf', 36) # 填充畫板 for x in range(width): for y in range(height): draw.point((x, y), fill=rnd_bg_color()) # 填充文字 for n in range(5): draw.text((60 * n + 25, 12), rnd_chr(chr_set), fill=rnd_chr_color(), font=font) # 對圖像內容進行模糊后存儲 image = image.filter(ImageFilter.BLUR) image.save('./random_code.jpg', 'jpeg')if __name__ == "__main__": main()
新聞熱點
疑難解答