import random
from PIL import Image, ImageDraw, ImageFont
class VerifyCode(object):
"""
params:
width:图片宽度
height:图片高度
char_num:图片随机字符的个数
noise_show:是否图片显示线条以及圆点干扰
noise_num:线条或者圆点的数量
font:字符所采用的字体,可以根据需要自己设置,同级文件需要有该ttf字体文件
return 产生的随机字符串
"""
def __init__(self, width=200, height=40, char_num=4, noise_show=True, noise_num=5,font='calibrili.ttf',img_name='1.png'):
self.width = width
self.height = height
self.char_num = char_num
self.noise_show = noise_show
self.noise_num = noise_num
self.font=font
self.img_name=img_name
def get_random_color(self):
"""产生随机颜色"""
return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
def create_img_code(self):
img = Image.new('RGB', (self.width, self.height), color=self.get_random_color())
draw = ImageDraw.Draw(img)
kumo_font = ImageFont.truetype(self.font, size=28)
valid_code_str = ''
for i in range(self.char_num):
random_num = str(random.randint(0, 9))
random_low_alpha = chr(random.randint(97, 122)) # A-Z
random_high_alpha = chr(random.randint(65, 90)) # a-z
random_char = random.choice([random_num, random_low_alpha, random_high_alpha])
draw.text((i * (self.width // self.char_num) + 20, self.char_num), random_char, self.get_random_color(),
font=kumo_font)
# 保存验证码字符串
valid_code_str += random_char
# 噪点噪线
if self.noise_show:
for i in range(self.noise_num):
x1 = random.randint(0, self.width)
x2 = random.randint(0, self.width)
y1 = random.randint(0, self.height)
y2 = random.randint(0, self.height)
draw.line((x1, y1, x2, y2), fill=self.get_random_color())
for i in range(self.noise_num):
draw.point([random.randint(0, self.width), random.randint(0, self.height)],
fill=self.get_random_color())
x = random.randint(0, self.width)
y = random.randint(0, self.height)
draw.arc((x, y, x + 4, y + 4), 0, 90, fill=self.get_random_color())
img.save(self.img_name, 'png')
return valid_code_str
if __name__ == '__main__':
code = VerifyCode(200, 40, 5, True, 10,img_name='2.jpg') # 返回产生的字符串
print(code.create_img_code())
python小功能--实现图片验证码的封装
最新推荐文章于 2023-06-06 09:53:00 发布