python模块PIL-获取带噪点噪线的随机验证码

from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from io import BytesIO

import random

class ValidCodeImg:
"""
生成一个经过降噪后的随机验证码的图片
:return 生成图片的bytes类型的数据
"""

def __init__(self, width=175, height=35, code_count=5,
             font_size=32, point_count=10, line_count=3,
             img_format='png'):
    # width: 图片宽度 单位px
    self.width = width
    # height: 图片高度 单位px
    self.height = height
    # code_count: 验证码个数
    self.code_count = code_count
    # font_size: 字体大小
    self.font_size = font_size
    # point_count: 噪点个数
    self.point_count = point_count
    # line_count: 划线个数
    self.line_count = line_count
    # img_format: 图片格式
    self.img_format = img_format

@staticmethod
def getrandomcolor():
    """获取一个随机颜色-(r,g,b)格式"""
    cor_r = random.randint(0, 255)
    cor_g = random.randint(0, 255)
    cor_b = random.randint(0, 255)
    return cor_r, cor_g, cor_b

@staticmethod
def getrandomstr():
    """获取一个随机字符串"""
    # 获取一个0-9的随机书
    num_str = str(random.randint(0, 9))
    # 获取一个A-Z的随机大写字母,65-90是大写字母的ascii码,通过chr转换成对应的字符
    upper_str = chr(random.randint(65, 90))
    # 获取一个a-z的随机小写字母,97-122是小写的ascii码,通过chr转换成对应的字符
    lower_str = chr(random.randint(97, 122))
    # 通过random模块的choice方法随机从以上的随机数字,大写字母和小写字母中获取一个字符,并返回
    random_str = random.choice((num_str, upper_str, lower_str))
    return random_str

def getvalidcodeimg(self):
    """获取一个随机验证码图片"""
    # 通过Image.new(rgb格式, (图片的宽,图片的高), 颜色)获取一个Image对象
    img_obj = Image.new('RGB', (self.width, self.height), self.getrandomcolor())
    print(img_obj)
    # 通过ImageDraw.Draw(Image对象)获取一个画笔对象
    draw = ImageDraw.Draw(img_obj)

    # 通过ImageFont.truetype(字体文件路径, 字体大小)获取一个字体对象
    font = ImageFont.truetype(r'\static\font\STXINGKA.TTF', size=self.font_size)

    tmp_list = []  # 用于存储随机字符串
    for i in range(self.code_count):
        random_char = self.getrandomstr()
        # 在图片上写入得到的随机字符串,这样字符之间才会有距离,不会叠加
        # 通过画笔对象的text方法,即 draw.text((x, y), 字符串, 颜色, 字体)
        draw.text((10 + i * 32, -2), random_char, self.getrandomcolor(), font=font)
        # 将随机字符串保存
        tmp_list.append(random_char)

    # 将所有的字符串拼接,稍后返回,用于校验用户录入的记录是否正确
    valid_str = ''.join(tmp_list)

    # 噪线的生成
    for i in range(self.line_count):
        # 噪线的起点横坐标和纵坐标
        x1 = random.randint(0, self.width)
        y1 = random.randint(0, self.height)
        # 噪线的终点横坐标和纵坐标
        x2 = random.randint(0, self.width)
        y2 = random.randint(0, self.height)
        # 通过画笔对象draw.line((起点的xy, 终点的xy), fill='颜色')来划线
        draw.line((x1, y1, x2, y2), fill=self.getrandomcolor())

    # 噪点的生成
    for i in range(self.point_count):
        draw.point([random.randint(0, self.width), random.randint(0, self.height)], fill=self.getrandomcolor())
        x = random.randint(0, self.width)
        y = random.randint(0, self.height)
        draw.arc((x, y, x + 4, y + 4), 0, 40, fill=self.getrandomcolor())

    # 将生成的图片保存到内存中
    f = BytesIO()
    img_obj.save(f, self.img_format)
    data = f.getvalue()
    f.close()

    return data, valid_str

# 测试

if name == ‘main‘:

img = ValidCodeImg()

data, valid_str = img.getvalidcodeimg()

print(valid_str)

with open(r‘E:\Desktop\code_test.png‘, ‘wb‘) as f:

f.write(data)

原文地址:https://www.cnblogs.com/xiaodan1040/p/12235323.html

时间: 2024-07-31 10:15:25

python模块PIL-获取带噪点噪线的随机验证码的相关文章

python的内置模块random随机模块方法详解以及使用案例(五位数随机验证码的实现)

1.random(self): Get the next random number in the range [0.0, 1.0) 取0到1直接的随机浮点数 import random print(random.random()) C:\python35\python3.exe D:/pyproject/day21模块/random随机模块.py 0.3105503800442595 2.randint(self, a, b) Return random integer in range [a

Python模块--PublicSuffix <获取URL的域名>

.com/.cn/.org之类的域名很好解决 类似.com.cn/.org.cn类似的域名没有直接的办法解决,本想搜集所有的顶级域名生成list然后使用正则匹配,却发现了这个. PublicSuffix 基本的用法在介绍里面都有,但是需要注意这里面的几个坑,就是一条URL不能直接往里面塞,否则塞进去不识别的吐出来还是未识别的字符串. http://www.baidu.com/ www.baidu.com/ www.baidu.com#pictures www.baidu.com/search?w

python模块之PIL模块(生成随机验证码图片)

PIL简介 什么是PIL PIL:是Python Image Library的缩写,图像处理的模块.主要的类包括Image,ImageFont,ImageDraw,ImageFilter PIL的导入 首先需要安装一下pillow包 pip install pillow 然后就可以调用PIL里的类了 from PIL import Image from PIL import ImageFont from PIL import ImageDraw from PIL import ImageFilt

Python模块:PIL

PIL:是Python Image Library的缩写,图像处理的模块.Image,ImageFont,ImageDraw,ImageFilter Image模块: 常用方法: open() #打开图片 new(mode,size,color) #创建新图片 save("test.gif","GIF") #保存(新图片路径和名称,保存格式) size() #获取图片大小 thumbnail(weight,high) #缩放图片大小(宽,高) show() #显示图

python的os模块批量获取目标路径下的文件名

目前在做一个项目开发与变更专项稽核,但是所抽取的目标项目,样本所附电子版文件上千个,需要判断文档完整性,就需要所有文档名清单. python的os模块好像是对这块比较擅长,就去翻了下文档,试着写了,效果还可以. 1 import os 2 3 #通过文件获取目标路径 4 file2=open(r'd:\dirname.txt','r') 5 a=file2.readlines() 6 file2.close() 7 8 #遍历目标路径下文件路径及名字,并写入新文件abc.txt 9 file1=

Python使用PIL模块生成随机验证码

PIL模块的安装 pip3 install pillow 生成随机验证码图片 import random from PIL import Image, ImageDraw, ImageFont from io import BytesIO def random_str(): ''' 生成随机字符 :return:随机字符 ''' random_int = str(random.randint(0,9)) random_up = chr(random.randint(65,90)) random_

python模块介绍

adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheetahcherrypy:一个WEB frameworkctypes:用来调用动态链接库DBUtils:数据库连接池django:一个WEB frameworkdocutils:用来写文档的dpkt:数据包的解包和组包MySQLdb:连接MySQL数据库的py2exe:用来生成windows可执行文件Pylons:我们领导推荐的web frameworkpysql

常用的python模块及安装方法

adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheetahcherrypy:一个WEB frameworkctypes:用来调用动态链接库DBUtils:数据库连接池django:一个WEB frameworkdocutils:用来写文档的dpkt:数据包的解包和组包MySQLdb:连接MySQL数据库的py2exe:用来生成windows可执行文件Pylons:我们领导推荐的web frameworkpysql

转 《python开发_常用的python模块及安装方法》

http://www.cnblogs.com/hongten/p/hongten_python_more_modules.html adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheetahcherrypy:一个WEB frameworkctypes:用来调用动态链接库DBUtils:数据库连接池django:一个WEB frameworkdocutils:用来写文档的dpkt:数据包的解包和组包MySQLdb: