[关闭]
@chengweihuang 2019-03-07T00:52:10.000000Z 字数 948 阅读 562

验证码

未分类


  1. import random
  2. import string
  3. from PIL import Image, ImageFont, ImageDraw, ImageFilter
  4. def rnd_Color(): # 随机颜色
  5. return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))
  6. def gene_text(): # 生成4位验证码
  7. return ''.join(random.sample(string.ascii_letters+string.digits, 4))
  8. def draw_lines(draw, num, width, height): # 划线
  9. for num in range(num):
  10. x1 = random.randint(0, width / 2)
  11. y1 = random.randint(0, height / 2)
  12. x2 = random.randint(0, width)
  13. y2 = random.randint(height / 2, height)
  14. draw.line(((x1, y1), (x2, y2)), fill='black', width=1)
  15. def get_verify_code():
  16. #生成验证码图形
  17. code = gene_text()
  18. # 图片大小120×50
  19. width, height = 120, 50
  20. # 新图片对象
  21. im = Image.new('RGB',(width, height),'white')
  22. # 字体
  23. font = ImageFont.truetype('app/static/mplus-1m-regular.woff2.ttf', 40)
  24. # draw对象
  25. draw = ImageDraw.Draw(im)
  26. # 绘制字符串
  27. for item in range(4):
  28. draw.text((5+random.randint(-3,3)+23*item, 5+random.randint(-3,3)),
  29. text=code[item], fill=rnd_Color(),font=font )
  30. # 划线
  31. # 高斯模糊 draw_lines(draw, 2, width, height)
  32. im = im.filter(ImageFilter.GaussianBlur(radius=1.5))
  33. return im, code
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注