python小功能--实现图片验证码的封装

import random
from PIL import Image, ImageDraw, ImageFont


class VerifyCode(object):
    """
               params:
               width:图片宽度
               height:图片高度
               char_num:图片随机字符的个数
               noise_show:是否图片显示线条以及圆点干扰
               noise_num:线条或者圆点的数量
               font:字符所采用的字体,可以根据需要自己设置,同级文件需要有该ttf字体文件
               return 产生的随机字符串
    """

    def __init__(self, width=200, height=40, char_num=4, noise_show=True, noise_num=5,font='calibrili.ttf',img_name='1.png'):
        self.width = width
        self.height = height
        self.char_num = char_num
        self.noise_show = noise_show
        self.noise_num = noise_num
        self.font=font
        self.img_name=img_name
    def get_random_color(self):
        """产生随机颜色"""
        return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))

    def create_img_code(self):
        img = Image.new('RGB', (self.width, self.height), color=self.get_random_color())
        draw = ImageDraw.Draw(img)
        kumo_font = ImageFont.truetype(self.font, size=28)

        valid_code_str = ''
        for i in range(self.char_num):
            random_num = str(random.randint(0, 9))
            random_low_alpha = chr(random.randint(97, 122))  # A-Z
            random_high_alpha = chr(random.randint(65, 90))  # a-z
            random_char = random.choice([random_num, random_low_alpha, random_high_alpha])
            draw.text((i * (self.width // self.char_num) + 20, self.char_num), random_char, self.get_random_color(),
                      font=kumo_font)
            # 保存验证码字符串
            valid_code_str += random_char
        # 噪点噪线
        if self.noise_show:
            for i in range(self.noise_num):
                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.get_random_color())

            for i in range(self.noise_num):
                draw.point([random.randint(0, self.width), random.randint(0, self.height)],
                           fill=self.get_random_color())
                x = random.randint(0, self.width)
                y = random.randint(0, self.height)
                draw.arc((x, y, x + 4, y + 4), 0, 90, fill=self.get_random_color())
        img.save(self.img_name, 'png')
        return valid_code_str


if __name__ == '__main__':
    code = VerifyCode(200, 40, 5, True, 10,img_name='2.jpg')  # 返回产生的字符串
    print(code.create_img_code())

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值