python生成图片验证码

  1. 类初始化
class VerifyCode:
    def __init__(self, width=100, height=40, size=4):
        # 验证码宽度、高度、字符个数
        self.width = width
        self.height = height
        self.size = size
  1. 生成随机颜色
    def __rand_color(self, low, high):
    	# RGB颜色样式
        return random.randint(low, high), random.randint(low, high), random.randint(low, high)
  1. 创建画布
    def generate(self):
        # 颜色模式、大小(宽,高)、颜色
        self.im = Image.new("RGB", (self.width, self.height), self.__rand_color(200, 250))
  1. 创建画笔
self.pen = ImageDraw.Draw(self.im)
  1. 生成验证码字符
self.rand_string()

函数为:

    def rand_string(self):
    	# 字符集,大小写字母和数字
        chr_s = string.ascii_letters + string.digits
        # 从字符集中取出指定个数的字符,并拼接成字符串
        self.__code = "".join(random.sample(chr_s, self.size))
        print(self.__code)
  1. 画验证码
self.draw_code()

函数为:

    def draw_code(self):
        # 获取字体,参数为字体、字号、编码
        font_c = ImageFont.truetype("simkai.ttf", size=18, encoding='utf-8')
        # 每个字符的宽度
        width = (self.width - 10) / self.size
        for i in range(self.size):
            x = 10 + i * width
            y = 15
            # 参数为字符坐标、字符、字体、字体颜色
            self.pen.text((x, y), self.__code[i], font=font_c, fill=self.__rand_color(20, 50))
  1. 画干扰点
self.__draw_point()

函数为:

    def __draw_point(self):
        for i in range(200):
            x = random.randint(1, self.width - 1)
            y = random.randint(1, self.height - 1)
            # 参数为点的坐标、点的颜色
            self.pen.point((x, y), fill=self.__rand_color(120, 180))
  1. 画干扰线
self.__draw_line()

函数为:

    def __draw_line(self):
        for i in range(5):
            x1 = random.randint(1, self.width - 1)
            x2 = random.randint(1, self.width - 1)
            y1 = random.randint(1, self.height - 1)
            y2 = random.randint(1, self.height - 1)
            # 参数为两个点的坐标(用于划线), 线的颜色、线的宽度
            self.pen.line([(x1, y1), (x2, y2)], fill=self.__rand_color(150, 180), width=1)
  1. 保存图片
self.im.save('code.png')

程序入口

if __name__ == '__main__':
    vc = VerifyCode()
    vc.generate()

结果示例:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值