python生成随机验证码

  工具        

pillow模块

安装:pip install pillow

  封装一个产生随机验证码的类      

 1 from PIL import Image, ImageDraw, ImageFont, ImageFilter
 2 import random
 3 
 4 
 5 class ConfirmCode(object):
 6 
 7     def __init__(self, width, height, save_path, font, font_size, distance):
 8         self.width = width
 9         self.height = height
10         self.save_path = save_path
11         self.font = font
12         self.font_size = font_size
13         self.distance = distance
14 
15     # 随机字母
16     def rnd_char(self):
17         return chr(random.randint(65, 90))
18 
19     # 背景颜色
20     def bg_color(self):
21         return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))
22 
23     # 文字颜色
24     def text_color(self):
25         return (random.randint(37, 127), random.randint(37, 137), random.randint(37, 137))
26 
27     # 生成验证码图片
28     def code_image(self):
29         image = Image.new("RGB", (self.width, self.height), (255, 255, 255))
30         # 创建Font对象
31         font = ImageFont.truetype(self.font, self.font_size)
32         # 创建Draw对象
33         draw = ImageDraw.Draw(image)
34         # 填充每一个像素
35         for x in range(self.width):
36             for y in range(self.height):
37                 draw.point((x, y), fill=self.bg_color())
38         # 输出文字
39         # 计算每个字体大小
40         size = self.width / 4
41         for t in range(4):
42             draw.text((size*t + self.distance, 10), self.rnd_char(), font=font, fill=self.text_color())
43         # 模糊
44         image = image.filter(ImageFilter.BLUR)
45         image.save(self.save_path, "jpeg")
46 
47 
48 
49 # 使用
50 obj = ConfirmCode(240, 60, "code.jpg", 'arial.ttf', 38, 20)
51 obj.code_image()

参数

  • width: 生成验证码区域的宽度
  • height: 生成验证码区域的高度
  • save_path: 保存图片的路径
  • font: 字体样式
  • font_size: 字体大小
  • distance: 每个字之间的间距大小

效果图

 

posted @ 2018-04-21 23:44  Jin同学  阅读(992)  评论(0)    收藏  举报