zoukankan      html  css  js  c++  java
  • python之使用PIL模块制作随机验证码

    制作随机验证码,需要如下知识点:

    1、随机验证码的制作(这里用的是random模块随机产生字符)

    2、图片的制作

    3、随机直线干扰项

    4、其他随机干扰项

    代码如下:

    from PIL import Image
    from PIL import ImageDraw
    from PIL import ImageFont
    import random
    
    #随机颜色 def get_random_color(): r = random.randint(0,255) g = random.randint(0,255) b = random.randint(0,255) return (r,g,b)
    #随机位置 def get_random_position(x,y): x = random.randint(0,x - 50) y = random.randint(0,y - 15) return (x,y)
    #线条随机俩个坐标 def get_random_line_position(x,y): x1 = random.randint(0,x) y1 = random.randint(0,y) x2 = random.randint(0,x) y2 = random.randint(0,y) return (x1,y1,x2,y2) def get_random_eci_position(x,y): x1 = random.randint(0,x) y1 = random.randint(0,y) x2 = x1 + 4 y2 = y1 + 4 return (x1,y1,x2,y2)
    #随机字符 def get_random_str(): num = str(random.randint(0,9)) low_letter = chr(random.randint(97,122)) upper_letter = chr(random.randint(65,90)) #print(num,low_letter,upper_letter) randomStr = random.choice([num,low_letter,upper_letter]) return randomStr x = 200 y = 60 #创建一个随机颜色的图形 img = Image.new('RGB',(x,y),get_random_color()) #在图形上随机位置显示4个随机颜色的文字 draw = ImageDraw.Draw(img) font = ImageFont.truetype('segoeuib.ttf',20) randomStr = '' for i in range(4): v = get_random_str() randomStr += v #print(randomStr) draw.text(get_random_position(x,y),randomStr,get_random_color(),font = font) #在图形上随机位置显示随机颜色的直线 for i in range(8): draw.line(get_random_line_position(x,y),get_random_color()) draw.ellipse(get_random_eci_position(x,y),get_random_color()) draw.arc(get_random_line_position(x,y),0,90,get_random_color()) img.show()

    执行效果如下:

    关于本篇内容如有转载请注明出处;技术内容的探讨、纠错,请发邮件到70907583@qq.com
  • 相关阅读:
    LeetCode(123) Best Time to Buy and Sell Stock III
    LeetCode(122) Best Time to Buy and Sell Stock II
    LeetCode(147) Insertion Sort List
    360兼容模式不支持hidden属性的问题
    第一个博客,用来勉励自己,加油
    【LGR-059】洛谷7月月赛题解
    Codechef July Challenge 2019 Division 1题解
    AtCoder Grand Contest 035
    Comet OJ
    2019-7-3 感记
  • 原文地址:https://www.cnblogs.com/watertaro/p/9074501.html
Copyright © 2011-2022 走看看