1. 程式人生 > 實用技巧 >簡單的圖片驗證碼生成器

簡單的圖片驗證碼生成器

圖片驗證碼生成器

from PIL import ImageDraw
from PIL import ImageFont
from PIL import Image
import random


class CheckCode:
    def __init__(self, width=242, height=38, code_count=5, font_size=32, point_count=20, line_count=3,
                 img_format='png'):
        """
        可以生成一個經過降噪後的隨機驗證碼的圖片
        :param width: 圖片寬度 單位px
        :param height: 圖片高度 單位px
        :param code_count: 驗證碼個數
        :param font_size: 字型大小
        :param point_count: 噪點個數
        :param line_count: 劃線個數
        :param img_format: 圖片格式
        :return 生成的圖片的bytes型別的data
        """
        self.width = width
        self.height = height
        self.code_count = code_count
        self.font_size = font_size
        self.point_count = point_count
        self.line_count = line_count
        self.img_format = img_format

    @staticmethod
    def getRandomColor():
        """獲取隨機顏色(r,g,b)"""
        return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)

    @staticmethod
    def getRandomStr():
        """獲取一個隨機字串,每個字元的顏色也是隨機的"""
        random_num = str(random.randint(0, 9))
        random_low_alpha = chr(random.randint(97, 122))
        random_upper_alpha = chr(random.randint(65, 90))
        random_char = random.choice([random_num, random_low_alpha, random_upper_alpha])
        return random_char

    def getValidCodeImg(self):
        # 獲取一個Image物件,引數分別是RGB模式。寬240,高38,隨機顏色
        image = Image.new('RGB', (self.width, self.height), (255, 255, 255))

        # 獲取一個畫筆物件,將圖片物件傳過去
        draw = ImageDraw.Draw(image)

        # 獲取一個font字型物件引數是ttf的字型檔案的目錄,以及字型的大小
        font = ImageFont.truetype(random.choice(["static/font/GothamNights.ttf", "static/font/Amiable.ttf", "static/font/FrankfurterMediumStd.otf"]), size=self.font_size)

        temp = []
        for i in range(self.code_count):
            # 獲取隨機字元
            random_char = self.getRandomStr()
            # 在圖片上一次寫入得到的隨機字串,引數是:定位,字串,顏色,字型
            draw.text((25 + i * 40, 4), random_char, self.getRandomColor(), font=font)

            # 儲存隨機字元,以供驗證使用者輸入的驗證碼是否正確時使用
            temp.append(random_char)
        valid_str = ''.join(temp)

        # 噪點噪線
        # 劃線
        for i in range(self.line_count):
            x1 = random.randint(0, self.width)
            x2 = random.randint(0, self.width)
            y1 = random.randint(0, self.height)
            y2 = random.randint(0, self.height)
            draw.line((x1, y1, x2, y2), fill=self.getRandomColor())

        # 畫點
        for i in range(self.point_count):
            draw.point([random.randint(0, self.width), random.randint(0, self.height)], fill=self.getRandomColor())
            x = random.randint(0, self.width)
            y = random.randint(0, self.height)
            draw.arc((x, y, x + 4, y + 4), 0, 90, fill=self.getRandomColor())

        # 在記憶體生成圖片
        from io import BytesIO
        f = BytesIO()
        image.save(f, self.img_format)
        data = f.getvalue()
        f.close()
        return data, valid_str