【Python】生成随机的图形验证码

制作缘由

突然想做一个图形验证码识别,所以想先写一个生成随机的图形验证码。

验证码结果预览

有一说一,这验证码略阴间。。。。
验证码1
验证码2

代码演示

写完后只是粗略地测试了一下,可能会有一点bug。如果有bug及代码修改方式希望能告知一下,谢谢!!!!

# 导入random模块
import random

# 导入Image,ImageDraw,ImageFont模块
from PIL import Image, ImageDraw, ImageFont, ImageFilter

chr_list = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
ttf_list = ['ALGER.TTF','ARIALNI.TTF','BRADHITC.TTF','CHILLER.TTF']
def rnd_chr(chr_list,chr_len):#生成随机字符
    return random.sample(chr_list,chr_len)

def rnd_font(font_list = ttf_list):#生成随机字体
    return random.choice(font_list)

def rnd_color():#生成随机色
    return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))

def check_code(width=120, height=30, chr_len=4, font_list=ttf_list, font_size=28):
    img = Image.new(mode='RGB', size=(width, height), color=(255, 255, 255))
    draw = ImageDraw.Draw(img, mode='RGB')
    code = rnd_chr(chr_list,chr_len)
    #写文字
    for i in range(chr_len):
        h = random.randint(0, 4)
        draw.text([i * width / chr_len, h], code[i], font=ImageFont.truetype(rnd_font(), font_size), fill=rnd_color())

    # 写干扰点
    for i in range(40):
        draw.point([random.randint(0, width), random.randint(0, height)], fill=rnd_color())

    # 写干扰圆圈
    for i in range(40):
        draw.point([random.randint(0, width), random.randint(0, height)], fill=rnd_color())
        x = random.randint(0, width)
        y = random.randint(0, height)
        draw.arc((x, y, x + 4, y + 4), 0, 90, fill=rnd_color())

    # 画干扰线
    for i in range(5):
        x1 = random.randint(0, width)
        y1 = random.randint(0, height)
        x2 = random.randint(0, width)
        y2 = random.randint(0, height)

        draw.line((x1, y1, x2, y2), fill=rnd_color())

    img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)
    return img, ''.join(code)

if __name__ == '__main__':
    img,code = check_code()
    img.show()
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值