制作随机字母与数字图片验证码
模块须知区
random随机模块:http://www.cnblogs.com/L5251/articles/8274099.html
pillow图像处理基础模块:http://www.cnblogs.com/L5251/articles/8619849.html
建议查询以上两篇博客
官网网址:https://pillow.readthedocs.io/en/latest/reference/Image.html#
代码区
生成随机RGB色值函数
def get_random_color(): ret = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) return ret
生成验证图片函数
def get_valid_img(request): # 生成随机颜色的底板 image = Image.new('RGB', (200, 46), get_random_color()) # 创建画笔 draw = ImageDraw.Draw(image) # 定义使用的字体(第一个参数为下载的字体路径,第二个参数为字体大小) font = ImageFont.truetype('/static/font/KGSecondChancesSketch.ttf', size=32) # 生成五个随机数字并存储 temp = [] 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((24 + i * 36, 0), random_char, get_random_color(), font=font) # 保存随机字符串 temp.append(random_char) width = 200 height = 46 # 产生噪线 for lines 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 spot in range(20): 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()) # 在内存中生成图片(可不写) memory = io.BytesIO() image.save(memory, "png") data = memory.getvalue() memory.close() # 格式化列表成字符串 valid_str = ''.join(temp) print(valid_str) print('='*120)
浏览器界面点击验证码图片自动更新图片方法
PS:一定要引入jQuery样式
# HTML区 <div class="col-md-5"> <img style="width:200px;height:46px;margin-top:25px;border-radius:5px;" src="{% url 'get_valid_img' %}" id="valid_code_img" alt="图片未加载出"> </div> # js脚本区
<script> $('#valid_code_img').on('click', function () { $(this)[0].src +='?'; }) </script> # 解释利用img属性!加问号网页地址不变,但可以实现刷新

浙公网安备 33010602011771号