• Python 生成4位验证码图片


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

    # 字体的位置
    font_path = "/Library/Fonts/Arial.ttf"
    # 验证码的位数
    number = 4
    # 生成图片的大小
    size = (100,30)
    # 图片背景颜色-白色
    bgcolor = (255,255,255)
    # 验证码字体颜色——蓝色
    fontcolor = (0,0,255)
    # 干扰线的颜色——红色
    linecolor = (255,0,0)
    # 是否加入干扰线
    draw_line = True
    # 图片上干扰线的颜色
    line_number = (1,5)

    def gene_text():
    # 获取26个英文字母
    source = list(string.ascii_letters)
    for index in range(0, 10):
    # 获取10个数字
    source.append(str(index))
    return ''.join(random.sample(source, number)) # number是生成验证码的位数


    #用来绘制干扰线
    def gene_line(draw,width,height):
    begin = (random.randint(0, width), random.randint(0, height))
    end = (random.randint(0, width), random.randint(0, height))
    draw.line([begin, end], fill = linecolor)

    #生成验证码
    def gene_code(k):
    # 宽和高
    width,height = size
    # 创建图片
    image = Image.new('RGBA',(width,height),bgcolor)
    # 验证码的字体
    font = ImageFont.truetype(font_path,25)
    # 创建画笔
    draw = ImageDraw.Draw(image)
    # 生成字符串
    text = gene_text()
    font_width, font_height = font.getsize(text)
    # 填充字符串
    draw.text(((width - font_width) / number, (height - font_height) / number),text,
    font= font,fill=fontcolor)
    if draw_line:
    gene_line(draw,width,height)
    # 创建扭曲
    image = image.transform((width+20,height+10), Image.AFFINE, (1,-0.3,0,-0.1,1,0),Image.BILINEAR)
    # 滤镜,边界加强
    image = image.filter(ImageFilter.EDGE_ENHANCE_MORE)
    # 保存验证码图片
    image.save('%d.png'%k)

    if __name__ == "__main__":
    # 循环创建验证码图片
    for i in range(0,1000):
    gene_code(i)
  • 相关阅读:
    __weak
    c++界面设计皮肤工具
    执行游戏时出现0xc000007b错误的解决方法
    2.4.1-Java语言基础(常量)
    句法模式识别(一)-串文法
    一步一步写算法(之hash表)
    LaTeX新人教程,30分钟从全然陌生到基本入门
    初次当面试官的经历和感触
    Android入门第八篇之GridView(九宫图)
    Android-Cannot merge new index 66195 into a non-jumbo instruction的解决的方法
  • 原文地址:https://www.cnblogs.com/lcl15/p/7998701.html
Copyright © 2020-2023  润新知