1. 程式人生 > >用Python生成圖片驗證碼,

用Python生成圖片驗證碼,

用Python生成圖片驗證碼,
Python版本:Python3.6
在這裡插入圖片描述

程式碼如下:

# -*-coding:utf-8 -*-
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random
import os
import platform

class VerificationCode(object):
    '''用於生成隨機驗證碼'''
    
    def __init__(self, file_name):
        self.str_code = list(range(
65, 91)) self.str_code += list(range(97, 123)) self.str_code += list(range(48, 58)) self.file_name = file_name + '.png' # 生成隨機字元 a~z, A~z, 0~9 def random_str(self): return chr(random.choice(self.str_code)) # 生成隨機顏色: def random_color(self): return
random.randint(0, 245), random.randint(0, 245), random.randint(0, 245) # 生成驗證碼和圖片 def generate_code(self): # 240 x 60: width = 60 * 4 height = 60 image = Image.new('RGB', (width, height), (255, 255, 255)) # 根據作業系統獲取字型檔案 if platform.uname().system ==
'Windows': ttf = 'arial.ttf' elif platform.uname().system == 'Linux': ttf = '/usr/share/fonts/arial/ARIAL.TTF' font = ImageFont.truetype(ttf, 50) draw = ImageDraw.Draw(image) # 隨機生成兩條直線(一條貫穿上半部,一條貫穿下半部) draw.line((0, 0 + random.randint(0, height // 2), width, 0 + random.randint(0, height // 2)), fill=self.random_color()) draw.line((0, height - random.randint(0, height // 2), width, height - random.randint(0, height // 2)), fill=self.random_color()) # 輸出文字 code_str = '' for t in range(4): tmp = self.random_str() # print(tmp, ord(tmp)) draw.text((60 * t + 10, 10), tmp, font=font, fill=self.random_color()) code_str += tmp # 模糊處理 image = image.filter(ImageFilter.EDGE_ENHANCE_MORE) # 圖片儲存 base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) path_name = os.path.join(base_dir, 'static/images/', self.file_name) image.save(path_name, 'png') return code_str if __name__ == '__main__': ver_code = VerificationCode('驗證碼') code = ver_code.generate_code()