zoukankan      html  css  js  c++  java
  • 验证码的生成

    from PIL import Image, ImageDraw, ImageFont, ImageFile, ImageFilter
    import random

    def check_code(width=120,height=30,char_length=5,font_file='Monaco.ttf',font_size = 28):
    code = [] # 用来存放生成的验证码
    img= Image.new(mode='RGB',size=(width,height),color=(255,255,255)) # 生成一个图片
    draw = ImageDraw.Draw(img, mode=('RGB')) # 生成一个这个图片的画笔

    def rndChar():
    """生成一个字母"""
    return chr(random.randint(65,90))

    def rndColor():
    """生成一个随机的颜色"""
    return (random.randint(0,255),random.randint(0,255),random.randint(0,255))

    font = ImageFont.truetype(font_file,font_size) # 创建一个字体样式

    for i in range(char_length):
    """开始写文字"""
    char = rndChar() # 生成一个字母
    code.append(char) # 将字体保存
    h = random.randint(0,4)
    draw.text([i * width / char_length, h], char, font=font, fill=rndColor()) # 将这个字写上去

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


    for i in range(40):
    """画干扰圆"""
    x = random.randint(0, width)
    y = random.randint(0, height)
    draw.arc((x, y, x + 4, y + 4), 0, 90, fill=rndColor())

    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=rndColor())

    img = img.filter(ImageFilter.EDGE_ENHANCE_MORE) # 文件模糊滤镜处理
    return img, ''.join(code)

    image_object, code = check_code()

    stream = BytesIO()
    image_object.save(stream, 'png')
    stream.getvalue()
  • 相关阅读:
    javascript 之异常处理try catch finally--05
    javascript 之基本包装类型--04
    javascript 之基本数据类型、引用数据类型区别--02
    javascript 之数据类型--01
    CSS3 object-fit 图像裁剪
    jQuery.extend 使用函数
    ios 不支持iframe 解决方案
    python常用代码积累
    mysql日志类型
    python中列表 元组 字符串如何互相转换
  • 原文地址:https://www.cnblogs.com/KingOfCattle/p/12802133.html
Copyright © 2011-2022 走看看