首先,制作随机验证码需要引入随机模块,即random模块,并写出随机颜色函数,具体如下:
import random def get_random_color(): return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
之后我们引入Python的常用制图模块Pillow,pip install pillow一下,有些情况下某些模块下载后依然无法直接在项目中使用,此时我们需要前往settings(快捷键Ctrl+Alt+S)中手动添加Pillow模块至当前项目即可,
引入io模块,避免磁盘参与WEB工作,保证网页速度,
随机验证码用ASCII码生成即可,
def get_valid_code_img(request): from PIL import Image, ImageDraw, ImageFont from io import BytesIO import random img = Image.new("RGB", (270, 40), color=get_random_color()) draw = ImageDraw.Draw(img) kumo_font = ImageFont.truetype("static/font/kumo.ttf", size=32) valid_code_str = "" for i in range(5): random_num = str(random.randint(0, 9)) random_low_alpha = chr(random.randint(97, 122)) random_upper_alpha = chr(random.randint(65, 90)) random_char = random.choice([random_num, random_low_alpha, random_upper_alpha]) draw.text((i * 50 + 20, 4), random_char, get_random_color(), font=kumo_font) # 保存验证码字符串 valid_code_str += random_char
print("valid_code_str", valid_code_str) request.session["valid_code_str"] = valid_code_str f = BytesIO() img.save(f, "png") data = f.getvalue() return data
为了更贴近生产情况,我们应该添加噪点与噪线,代码如下,插入上方函数中任意处即可,
#噪点与噪线 width=270 height=40 for i in range(5): x1=random.randint(0,width) x2=random.randint(0,width) y1=random.randint(0,height) y2=random.randint(0,height) draw.line((x1,y1,x2,y2),fill=get_random_color()) for i in range(90): draw.point([random.randint(0, width), random.randint(0, height)], fill=get_random_color()) x = random.randint(0, width) y = random.randint(0, height) draw.arc((x, y, x + 4, y + 4), 0, 90, fill=get_random_color())
最后,引入到我们对应的html文件中,大功告成。
效果图直接放出,
原文地址:https://www.cnblogs.com/91joe/p/12327082.html
时间: 2024-10-09 22:31:01