首页 > 编程语言 >Python生成随机验证码

Python生成随机验证码

时间:2023-04-06 20:59:03浏览次数:38  
标签:code img randint Python random 验证码 width 随机 font

pip install pillow

 

实现代码

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


def check_code(width=120, height=30, char_length=5, font_file='kumo.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:
        """
        return chr(random.randint(65, 90))

    def rndColor():
        """
        生成随机颜色
        :return:
        """
        return (random.randint(0, 255), random.randint(10, 255), random.randint(64, 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):
        draw.point([random.randint(0, width), random.randint(0, height)], fill=rndColor())
        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)


if __name__ == '__main__':
    # 1. 直接打开
    # img,code = check_code()
    # img.show()

    # 2. 写入文件
    img, code = check_code()
    with open('code.png', 'wb') as f:
        img.save(f, format='png')

    # 3. 写入内存(Python3)
    # from io import BytesIO
    # stream = BytesIO()
    # img.save(stream, 'png')
    # stream.getvalue()

    # 4. 写入内存(Python2)
    # import StringIO
    # stream = StringIO.StringIO()
    # img.save(stream, 'png')
    # stream.getvalue()

    # pass

效果

 

 

标签:code,img,randint,Python,random,验证码,width,随机,font
From: https://www.cnblogs.com/HGNET/p/17294111.html

相关文章

  • 02:python-函数
     正文#1:调用内置函数#调用绝对值函数abs()intAbs=abs(-20)print(intAbs)#调用最大函数intMax=max(1,2,-1,10)print(intMax)#数据类型转换print(int('124'))#字符串转intprint(int(12.34))#float转intprint(str(12.34))#float转字符串......
  • Python小练习:权重初始化(Weight Initialization)
    Python小练习:权重初始化(WeightInitialization)作者:凯鲁嘎吉-博客园 http://www.cnblogs.com/kailugaji/调用Pytorch中的torch.nn.init.xxx实现对模型权重与偏置初始化。1.weight_init_test.py1#-*-coding:utf-8-*-2#Author:凯鲁嘎吉CoralGajic3#https://w......
  • 【转】python pip 换源阿里云
    via:pythonpip换源阿里云-知乎(zhihu.com)pip换源阿里云只需要在cmd输入一条命令:pipconfigsetglobal.index-urlhttps://mirrors.aliyun.com/pypi/simple ......
  • opencv-python 4.13. 霍夫线变换
    前言霍夫变换是一种特征检测(featureextraction),被广泛应用在图像分析(imageanalysis)、计算机视觉(computervision)以及数位影像处理(digitalimageprocessing)。霍夫变换(HoughTransform)是图像处理中的一种特征提取技术,它通过一种投票算法检测具有特定形状的物体。该过程......
  • Python字节
    python的文件操作中,一个中文字符等于3个字节。1B(byte,字节)=8bit(位)1KB(Kilobyte,千字节)=1024B =(10的3次方)B1MB(Megabyte,兆字节,百万字节,简称“兆”)=1024KB = (10的6次方)B1GB(GB,吉字节,千兆) = 1024MB1TB(TB,万亿字节,太字节) = 1024GB1PB(PB,千万亿字节,拍字节) ......
  • CS50-Python实验5,6
    Week5UnitTestsTestingmytwittr题目描述:测试ProblemSet2中Settingupmytwttr程序;题解:twttr.pydefmain():print("Output:",shorten(input("Input:")))defshorten(word):ans=""foriinword:ifi.lowe......
  • python系列007
    //使用类进行设备控制类文件内容importpyvisaimportnumpyasnpimporttimeclassPiDevice:def__init__(self):self.device_id=None#默认无设备连接deffind_device_address(self,device_id):rm=pyvisa.ResourceMa......
  • 20230406-Python-if判断-day4
    条件语句4月6场景假设:网吧上网去⽹吧进⻔想要上⽹必须做的⼀件事是做什么?(考虑重点)为什么要把身份证给⼯作⼈员?是不是就是为了判断是否成年?是不是如果成年可以上⽹?如果不成年则不允许上⽹?其实这⾥所谓的判断就是条件语句,即条件成⽴执⾏某些代码,条件不成⽴则不执⾏这些......
  • Python学习——Day1
      学习python与C语言相似,第一件事也是输出一个”HelloWorld"。  但是相比C语言,python的输出要简洁好多,他没有换行符\n也能自动换行,print()函数里字符串无论是使用单引号还是双引号结果都能正常输出且输出结果一样。  第二个就是注释,python则与C语言不同,这里用到......
  • 【Python从零到壹】Python条件语句详解
    欢迎大家来到互联网老辛的专栏《Python从零到壹》,在这里我将分享约300篇Python系列文章,所有文章都将结合案例、代码和作者的经验讲解,真心想把自己近十年的编程经验分享给大家,希望对您有所帮助,文章中不足之处也请海涵。从事教学工作以来,越来越觉得时间的宝贵,每届学生都要讲重复的课,......