1.安装Pillow库
pip install pillow
2.生成验证码
import random
import string
from io import BytesIO
from PIL import Image, ImageDraw, ImageFont
from BackgroundManager.settings import PICTURE_PATH
class PictureVerify:
def __init__(self,width=100,height=42,size=4):
"""
width: 验证码图片宽度
height: 验证码图片高度
size: 验证码图片字符数
"""
self.width = width
self.height = height
self.size = size
self.__code = ''
self.pen = None
"""
PICTURE_PATH:字体路径
size=25:字体大小
"""
self.font_tmp = ImageFont.truetype(PICTURE_PATH,size=25,encoding='utf-8')
def generate(self):
im = Image.new('RGB',(self.width,self.height),self.__rand_color(150))
self.pen = ImageDraw.Draw(im)
self.rand_string()
self.__draw_code()