vcode.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. # -*- coding: utf-8 -*-
  2. from io import BytesIO
  3. import random
  4. import string
  5. from PIL import Image, ImageFont, ImageDraw, ImageFilter
  6. '''
  7. 验证码处理
  8. '''
  9. def rndColor():
  10. '''随机颜色'''
  11. return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))
  12. def geneText():
  13. '''生成4位验证码'''
  14. return ''.join(random.sample(string.digits, 4)) #ascii_letters是生成所有字母 digits是生成所有数字0-9
  15. def drawLines(draw, num, width, height):
  16. '''划线'''
  17. for num in range(num):
  18. x1 = random.randint(0, width / 2)
  19. y1 = random.randint(0, height / 2)
  20. x2 = random.randint(0, width)
  21. y2 = random.randint(height / 2, height)
  22. draw.line(((x1, y1), (x2, y2)), fill='black', width=1)
  23. def getVerifyCode():
  24. '''生成验证码图形'''
  25. code = geneText()
  26. # 图片大小120×50
  27. width, height = 120, 50
  28. # 新图片对象
  29. im = Image.new('RGB', (width, height), 'white')
  30. # 字体
  31. font = ImageFont.truetype('./static/font/Arial.ttf', 40)
  32. # draw对象
  33. draw = ImageDraw.Draw(im)
  34. # 绘制字符串
  35. for item in range(4):
  36. draw.text((5 + random.randint(-3, 3) + 23 * item, 5 + random.randint(-3, 3)),
  37. text=code[item], fill=rndColor(), font=font)
  38. # 划线
  39. drawLines(draw, 2, width, height)
  40. return im, code