python PIL模块做纯数字验证码

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

class VerifyCode:
    def __init__(self,width=100,height=60,len=4):

        self.width = 100 if width < 0 else width
        self.height = 60 if height < 0 else height
        self.len = 4 if len < 0 or len > 5 else len
        self.pen = None  # 画笔
        self.__code = None  # 验证码字符串


    def generate_code(self):
        #1.生成画布
        im = Image.new("RGB", (self.width, self.height), self.__rand_color(160, 250))

        #2 生成画笔
        self.pen = ImageDraw.Draw(im)

        #3 生成验证码字符串
        self.__code = self.rand_string()

        #4 花验证码
        self.__draw_code()
        self.__draw_line()

        #5 画干扰项
        self.__disturb_point()

        #6 保存图片
        im.show()
        im.save('vc.png','PNG')

    def __draw_line(self):
        for i in range(5):
            x1 = randint(1,self.width-1)
            x2 = randint(1,self.width-1)
            y1 = randint(1,self.width-1)
            y2 = randint(1,self.width-1)
            self.pen.line([(x1,y1),(x2,y2)],fill=self.__rand_color(120,160))
    def __disturb_point(self):
        for i in range(500):
            x = randint(1,self.width-1)
            y = randint(1,self.height-1)
            self.pen.point([(x,y)],fill=self.__rand_color(120,160))

    def __rand_color(self,low,hight):
        # 随机颜色
        return randint(low,hight),randint(low,hight),randint(low,hight)
    def rand_string(self):
        # 纯数字验证
        string = ''
        for i in range(self.len):
            string += str(randint(0,9))
        return string


    def __draw_code(self):
        # 画验证码字符串
        for i in range(len(self.__code)):
            x = 10 + i * (self.width - 20) / self.len
            y = randint(10,25)
            font = ImageFont.truetype('simhei.ttf',size=25,encoding='utf-8')
            self.pen.text((x, y), self.__code[i], self.__rand_color(0, 90), font=font)


# vc = VerifyCode()
# vc.generate_code()


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值