1234567891011121314151617181920212223242526272829303132333435363738394041424344 |
- # -*- coding: utf-8 -*-
- from io import BytesIO
- import random
- import string
- from PIL import Image, ImageFont, ImageDraw, ImageFilter
- '''
- 验证码处理
- '''
- def rndColor():
- '''随机颜色'''
- return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))
- def geneText():
- '''生成4位验证码'''
- return ''.join(random.sample(string.digits, 4)) #ascii_letters是生成所有字母 digits是生成所有数字0-9
- def drawLines(draw, num, width, height):
- '''划线'''
- for num in range(num):
- x1 = random.randint(0, width / 2)
- y1 = random.randint(0, height / 2)
- x2 = random.randint(0, width)
- y2 = random.randint(height / 2, height)
- draw.line(((x1, y1), (x2, y2)), fill='black', width=1)
- def getVerifyCode():
- '''生成验证码图形'''
- code = geneText()
- # 图片大小120×50
- width, height = 120, 50
- # 新图片对象
- im = Image.new('RGB', (width, height), 'white')
- # 字体
- font = ImageFont.truetype('./static/font/Arial.ttf', 40)
- # draw对象
- draw = ImageDraw.Draw(im)
- # 绘制字符串
- for item in range(4):
- draw.text((5 + random.randint(-3, 3) + 23 * item, 5 + random.randint(-3, 3)),
- text=code[item], fill=rndColor(), font=font)
- # 划线
- drawLines(draw, 2, width, height)
- return im, code
|