1 utils.py
import random
def get_random_code():
code = ''
for i in range(5):
upper_char = chr(random.randint(65, 90))
lower_char = chr(random.randint(97, 122))
num_char = str(random.randint(0, 9))
res = random.choice([upper_char, lower_char, num_char])
code += res
return code
def get_random_rgb():
return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
2 生成验证码
from PIL import Image, ImageDraw, ImageFont
from io import BytesIO
import random
from .utils import get_random_code, get_random_rgb
def get_code(request):
width, hight = 300, 38
image_tmp = Image.new('RGB', (width, hight), get_random_rgb())
draw = ImageDraw.Draw(image_tmp)
img_font = ImageFont.truetype('./static/font/ss.ttf', 23)
code_str = get_random_code()
for i, item in enumerate(code_str):
draw.text((20 + i * 45, 0), item, fill=get_random_rgb(), font=img_font)
for i in range(50):
draw.point([random.randint(0, width), random.randint(0, hight)], fill=get_random_rgb())
x = random.randint(0, width)
y = random.randint(0, hight)
draw.arc((x, y, x + 4, y + 4), 0, 90, fill=get_random_rgb())
for i in range(6):
x1 = random.randint(0, width)
x2 = random.randint(0, width)
y1 = random.randint(0, hight)
y2 = random.randint(0, hight)
draw.line((x1, y1, x2, y2), fill=get_random_rgb())
my_io = BytesIO()
image_tmp.save(my_io, 'png')
return HttpResponse(my_io.getvalue())
效果图: