python使用 Captcha 模块来生成验证码图片

使用 Captcha 模块来生成验证码图片

安装就不多说了
pip3 install captcha

pip3 install captcha -i https://mirrors.aliyun.com/pypi/simple/

话不多说,直接上代码

import base64
import random
from io import BytesIO

from captcha.image import ImageCaptcha

seed = '123456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ'


def generate_captcha():
    """
    生成验证码
    验证码使用 4 位
    :return: 验证码图片的 base64 表示
    """

    captcha_str = ''.join(random.choice(seed) for _ in range(4))
    image = ImageCaptcha().generate_image(captcha_str)
    buffer = BytesIO()
    image.save(buffer, format='PNG')
    data = buffer.getvalue()
    return 'data:image/png;base64,' + base64.b64encode(data).decode()

if __name__ == '__main__':
    print(generate_captcha())

效果如图
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKAAAAA8CAIAAABuCSZCAAAZW0lEQVR4nOV925Mb13nn953T3QC6gcYMZgCSM6Q5ssmYpOJLpCUlWr5Q0tq0fJNkJ6lYW3aytdlKHvyQVOXZD/4HtmorTyl7t+JN5NrSypTsjS5eSSS1kSWZlpQokshIpDm8DMkBZjBAd58G0N3nfHk4DcxwBgNgeBvR+dVwiAH69OlzvvPdv3OAfiTgtwJzf/X7nQf/qzz612QVP+GVO//9v928vt48XNEv7nq++uG5VV/gJhI48ertC6cXn3984vBj2R27DLe0oeYyimXoYVCXjerSsZ+2fCGDJgBkx7eWv/Kd3M6Pk+N8CB/7Jt1qPWwagfXYLv3oBwCQ2b5r+k+/v9HhxY3FpXfeku8dzc+fqieZTruNRABoVqYnv/Kd3Mwebrs359kh8er6xfWT5Abeqi+MW9NNXyw+/7h+MXH4sWtoLoUfnXwlPvuv7bgNGCEaAAgA6PvixEv25A64aQS+gbN0syecQZeZ5n74g/aF0z1K3wJMHH4ss33X1H/5/oakkxR+VLvUmj0VXTojG7VEyoRZCfLlKxDd5KYI59sR6EciePdX1yMqrxnXIDak8OLapaVjP0vCphRNJXwZegAABID6F+Qmd0x+9Y9zM3tukg6+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2lAM3uO2aZZj8/O8vPPNjKYLeKaQrVHh6vJOWw9wuWLmMc89DZmU7t93B1IWN01VjE88X3RA2zMGbNaSodmnp+FOds+/EwkvCAIF1bepuegshMzk1duiRTHlKW0m6DPvaMJg7r//7CG4ZNvadDZsolKTwVehFtQtLx34S1RpKhASKgBAkt4vcKWB+zKhUJj//Leu6E/WjHA8898MfdC6eBoBrK1q+zsfTL0bpdDO/deUaIEUjqV3yj/5cLFyRYQNAGXbOLpVz934N8243NnJdX9UwCnduojDbaNe3GYFBn78h/HjhcuPEMaY898Bhq7yDOQXmjN2Q+4/InZsizK5BNVxroOPmY70Z1CXWLO+Wy1sBgNv569G1fTGKM7pZSnejkZAPKQdvrkH3ofV/rmFaPqQEhpv/nW//TvBvL/1IMaDhqTgAAAAASUVORK5CYII=

进程已结束,退出代码 0

参考来源:

https://blog.csdn.net/wi162yyxq/article/details/88200440

https://blog.csdn.net/chenfei3306/article/details/119317557

该函数库可以生成任意形式的数字字符类验证码,只要在创建对象时:

captcha = ImageCaptcha(fonts=[’/path/to/A.ttf’, ‘/path/to/B.ttf’])即可修改字体,利用该类中write函数,可以将任意长度数量的字符改为验证码。

精简步骤三行代码足以

#导入captcha包下的image文件中的ImageCaptcha类,使用之前先实例化

from captcha.image import ImageCaptcha

ic = ImageCaptcha()
ic.write('1a8c', '1a8c' + '.png', format='png')

深度的代码,批量化生成

import sys
import os
import shutil
import random
import time
from captcha.image import ImageCaptcha
 
#用于生成验证码的字符集
CHAR_SET = ['0','1','2','3','4','5','6','7','8','9']
#字符集的长度
CHAR_SET_LEN = 10
#验证码的长度,每个验证码由4个数字组成
CAPTCHA_LEN = 4
 
#验证码图片的存放路径
CAPTCHA_IMAGE_PATH = 'images/'
#用于模型测试的验证码图片的存放路径,它里面的验证码图片作为测试集
TEST_IMAGE_PATH = 'test/'
#用于模型测试的验证码图片的个数,从生成的验证码图片中取出来放入测试集中
TEST_IMAGE_NUMBER = 100
 
#生成验证码图片,4位的十进制数字可以有10000种验证码
def generate_captcha_image(charSet = CHAR_SET, charSetLen=CHAR_SET_LEN, captchaImgPath=CAPTCHA_IMAGE_PATH):   
    k  = 0
    total = 1
    for i in range(CAPTCHA_LEN):
        total *= charSetLen
        
    for i in range(charSetLen):
        for j in range(charSetLen):
            for m in range(charSetLen):
                for n in range(charSetLen):
                    captcha_text = charSet[i] + charSet[j] + charSet[m] + charSet[n]
                    image = ImageCaptcha()
                    image.write(captcha_text, captchaImgPath + captcha_text + '.png')//图片格式改成其他可能会有问题
                    k += 1
                    sys.stdout.write("\rCreating %d/%d" % (k, total))
                    sys.stdout.flush()
                    
#从验证码的图片集中取出一部分作为测试集,这些图片不参加训练,只用于模型的测试                    
def prepare_test_set():
    fileNameList = []    
    for filePath in os.listdir(CAPTCHA_IMAGE_PATH):
        captcha_name = filePath.split('/')[-1]
        fileNameList.append(captcha_name)
    random.seed(time.time())
    random.shuffle(fileNameList) 
    for i in range(TEST_IMAGE_NUMBER):
        name = fileNameList[i]
        shutil.move(CAPTCHA_IMAGE_PATH + name, TEST_IMAGE_PATH + name)
                        
if __name__ == '__main__':
    generate_captcha_image(CHAR_SET, CHAR_SET_LEN, CAPTCHA_IMAGE_PATH)
    prepare_test_set()
    sys.stdout.write("\nFinished")
    sys.stdout.flush()  

你可能感兴趣的:(python2021,python,captcha)