python随机生成验证码

需要导入pillow模块

from random import choice, randint

from PIL import Image, ImageDraw, ImageFont, ImageFilter

class VerifyCode(object):

"""生成验证码模块"""

def __init__(self, length=4, width=160, height=50, font_size=40):

self._random_code = '' # 验证码字符串

self._verify_code_image = None # PIL图片Image对象

self._length = length # 验证码长度

self._width = width # 图片宽度

self._height = height # 图片高度

self._font_size = font_size # 字体大小

self.random_code() # 初始化验证码字符

self.set_image() # 绘制图片

def random_code(self):

chars = '1234567890qwertyuiopasdfghjklzxcvbnm' # 验证码字符库

code = '' # 生成的验证码

for _ in range(self._length): # 循环随机取一个字符

code += choice(chars)

self._random_code = code # 赋值给当前对象的random_code属性

@staticmethod

def random_color(s=0, e=255):

return randint(0, 256), randint(0, 256), randint(0, 256)

def set_image(self):

# 创建画布

image = Image.new('RGB', (self._width, self._height), (255, 255, 255))

# 创建字体对象

font = ImageFont.truetype('arial.ttf', self._font_size)

# 创建画图对象

draw = ImageDraw.Draw(image)

# 随机生成噪点

for x in range(self._width):

for y in range(self._height):

temp = x + y + randint(0, 10)

if temp % 10 == 0:

draw.point((x, y), fill=self.random_color(0, 255))

# 字符添加

for t in range(self._length):

dev_x = randint(0, 5) # 随机左右浮动

dev_y = randint(0, 5) # 随机上下浮动

x, y = self._font_size * t + dev_x, dev_y

# 将字符通过随机颜色画到图片中

draw.text((x, y), self._random_code[t],

font=font, fill=self.random_color(0, 200))

# 高斯模糊

image = image.filter(ImageFilter.GaussianBlur)

# 将图片对象赋值给当前对象的verify_code_image属性

self._verify_code_image = image

@property

def verify_code(self):

return self._random_code

@property

def verify_image(self):

return self._verify_code_image

def get_verify(self):

return self._random_code, self._verify_code_image

if __name__ == '__main__':

v1 = VerifyCode()

print(v1.get_verify())

# ('tspf', <PIL.Image.Image image mode=RGB size=160x50 at 0x1AA45B00D68>)

python随机生成验证码

相关推荐