前端
//图片验证码主体
<div class="form-group">
<label for="">验证码</label>
<div class="row">
<div class="col-md-6">
<input type="text" id="id_code" class="form-control">
</div>
<div class="col-md-6">
<img src="/get_code/" height="35px" width="300px">
</div>
</div>
</div>
//图片验证码点击刷新
$(‘#id_img‘).click(function () {
let img_url = $(‘#id_img‘)[0].src
$(‘#id_img‘)[0].src = img_url + ‘?‘
})
后端
def get_random():
return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
def get_code(request):
# img = Image.new(‘RGB‘, (300, 30), get_random())
img = Image.new(‘RGB‘, (250, 30), (250, 250, 250))
# 第一个参数,是文字格式的文件,ttf格式,第二个参数是文字大小
img_font = ImageFont.truetype(‘./static/font/ss.TTF‘, 20)
# 拿到一个画板对象,把图片放到画板上,指定写的字的字体是什么
img_draw = ImageDraw.Draw(img)
# 在画板上写文字
# 随机生成5位 小写字母,大写字母,和数字
code = ‘‘
for i in range(5):
low_char = chr(random.randint(97, 122))
up_char = chr(random.randint(65, 90))
number_char = str(random.randint(0, 9))
res = random.choice([low_char, up_char, number_char])
code += res
img_draw.text((20 + i * 40, 0), res, fill=get_random(), font=img_font)
print(code)
request.session[‘code‘] = code
# 画点和线
# 画线和点圈
width = 250
height = 30
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)
# 在图片上画线
img_draw.line((x1, y1, x2, y2), fill=get_random())
for i in range(20):
# 画点
img_draw.point([random.randint(0, width), random.randint(0, height)], fill=get_random())
x = random.randint(0, width)
y = random.randint(0, height)
# 画弧形
img_draw.arc((x, y, x + 4, y + 4), 0, 90, fill=get_random())
bytes_io = BytesIO()
img.save(bytes_io, ‘png‘) # 写到内存中,需要传format,图片格式
return HttpResponse(bytes_io.getvalue()) # 把内容读出来
原文:https://www.cnblogs.com/shof/p/14646900.html