码迷,mamicode.com
首页 > 其他好文 > 详细

强大的验证码生成模块

时间:2018-05-08 22:28:40      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:and   int()   div   byte   random   不能   rand   gbk   unicode   

# 首先要安装PIL库  pip3 install pillow
from PIL import Image, ImageDraw, ImageFont, ImageFilter

import random
class CheckCode:
    def __init__(self, font_file, font_size=36, width=240, height=60, char_length=4, start_color_num=0,
                 end_color_num=255, is_simple=True):
        self.is_simple = is_simple
        self.font_file = font_file
        self.font_size = font_size
        self.width = width
        self.height = height
        self.char_length = char_length
        self.start_num = start_color_num
        self.end_num = end_color_num
        # 定义使用Image类实例化一个长为120px,宽为30px,基于RGB的(255,255,255)颜色的图片
        self.image = Image.new(RGB, (self.width, self.height), (255, 255, 255))
        # 创建Font对象:
        self.font = ImageFont.truetype(self.font_file, self.font_size)
        # 创建Draw对象:
        self.draw = ImageDraw.Draw(self.image)
        # 双下划綫的变量在类中不能直接访问起到保护的作用
        self.__code_text = []

    def get_random_code(self, time=1):
        """
        :param is_simple: 是否包含中文繁体字,默认不包含,True表示不包含
        :param time: 返回多少个
        :return: 返回一个随机字符列表
        """
        is_simple = self.is_simple
        codes = []
        for i in range(time):
            num = chr(random.randint(0x30, 0x39))  # 随机生成数字
            lowercase = chr(random.randint(0x61, 0x74))  # 随机生成小写字母
            capcase = chr(random.randint(0x41, 0x5a))  # 随机生成大写字母

            # Unicode编码的汉字,带繁体字 ,共2万多字
            zh = chr(random.randint(0x4e00, 0x9fbf))

            # gbk编码的简单汉字,无繁体字
            head = random.randint(0xb0, 0xf7)
            body = random.randint(0xa1, 0xf9)  # 在head区号为55的那一块最后5个汉字是乱码,为了方便缩减下范围
            val = f{head:x}{body:x}
            ch = bytes.fromhex(val).decode(gb2312)

            if is_simple:
                # code = random.choice([ch, num, lowercase, capcase])
                code = random.choice([ch, num, lowercase, capcase])
            else:
                code = random.choice([zh, num, lowercase, capcase])
            codes.append(code)
        return codes

    # 随机颜色:
    def rndColor(self, start, end, randomflag=True):
        """
        :param start:
        :param end:
        :param randomflag: 是否返回随机参数,
        :return:
        """
        return (random.randint(start, end), random.randint(start, end),
                random.randint(start, end))

    def rotate(self):
        self.image.rotate(random.randint(0, 90), expand=0)

    # 随机点
    def randPoint(self):
        return (random.randint(0, self.width), random.randint(0, self.height))

    # 随机线
    def randLine(self, num):
        draw = ImageDraw.Draw(self.image)
        for i in range(0, num):
            draw.line([self.randPoint(), self.randPoint()], self.rndColor(0, 255))
        del draw

    # 获取验证码
    def get_codes(self):
        return self.__code_text

    def draw_pic(self):
        # 填充每个像素:
        # 单一背景
        color = self.rndColor(0, 255)
        for x in range(self.width):
            for y in range(self.height):
                self.draw.point((x, y), fill=color)

        # 输出文字:
        codes = self.get_random_code(time=self.char_length)
        for ii in range(self.char_length):
            code = self.get_random_code()[0]
            self.__code_text.append(code)
            self.draw.text([random.randint(int((self.width / 2 - self.font_size / 2) / self.char_length * 2 * ii),
                                           int((self.width / 2 - self.font_size / 2) / self.char_length * 2 * (
                                                   ii + 1))), random.randint(0, self.height / 4)],
                           code, font=self.font, fill=self.rndColor(0, 255))
        # self.rotate()

        # 画出随机线
        self.randLine(5)

        # 模糊:
        # self.image = self.image.filter(ImageFilter.BLUR)

        # 保存
        self.image.save(code.jpg, jpeg)


# 这里的字体采用能识别中文的字体
font_file = ?C:\Windows\Fonts\simhei.ttf
checkcode = CheckCode(font_file=font_file, is_simple=False, char_length=random.randint(3, 7))
checkcode.draw_pic()

codes = checkcode.get_codes()

print(codes)

 

强大的验证码生成模块

标签:and   int()   div   byte   random   不能   rand   gbk   unicode   

原文地址:https://www.cnblogs.com/felixwang2/p/9010909.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!