- 类初始化
class VerifyCode:
def __init__(self, width=100, height=40, size=4):
# 验证码宽度、高度、字符个数
self.width = width
self.height = height
self.size = size
- 生成随机颜色
def __rand_color(self, low, high):
# RGB颜色样式
return random.randint(low, high), random.randint(low, high), random.randint(low, high)
- 创建画布
def generate(self):
# 颜色模式、大小(宽,高)、颜色
self.im = Image.new("RGB", (self.width, self.height), self.__rand_color(200, 250))
- 创建画笔
self.pen = ImageDraw.Draw(self.im)
- 生成验证码字符
self.rand_string()
函数为:
def rand_string(self):
# 字符集,大小写字母和数字
chr_s = string.ascii_letters + string.digits
# 从字符集中取出指定个数的字符,并拼接成字符串
self.__code = "".join(random.sample(chr_s, self.size))
print(self.__code)
- 画验证码
self.draw_code()
函数为:
def draw_code(self):
# 获取字体,参数为字体、字号、编码
font_c = ImageFont.truetype("simkai.ttf", size=18, encoding='utf-8')
# 每个字符的宽度
width = (self.width - 10) / self.size
for i in range(self.size):
x = 10 + i * width
y = 15
# 参数为字符坐标、字符、字体、字体颜色
self.pen.text((x, y), self.__code[i], font=font_c, fill=self.__rand_color(20, 50))
- 画干扰点
self.__draw_point()
函数为:
def __draw_point(self):
for i in range(200):
x = random.randint(1, self.width - 1)
y = random.randint(1, self.height - 1)
# 参数为点的坐标、点的颜色
self.pen.point((x, y), fill=self.__rand_color(120, 180))
- 画干扰线
self.__draw_line()
函数为:
def __draw_line(self):
for i in range(5):
x1 = random.randint(1, self.width - 1)
x2 = random.randint(1, self.width - 1)
y1 = random.randint(1, self.height - 1)
y2 = random.randint(1, self.height - 1)
# 参数为两个点的坐标(用于划线), 线的颜色、线的宽度
self.pen.line([(x1, y1), (x2, y2)], fill=self.__rand_color(150, 180), width=1)
- 保存图片
self.im.save('code.png')
程序入口
if __name__ == '__main__':
vc = VerifyCode()
vc.generate()
结果示例: