django网页调用摄像头实现实时画面监控数据前后端传递的完整代码案例
时间: 2024-05-31 12:07:34 浏览: 182
前端调用摄像头录像demo
由于Django是一个后端框架,它本身并不支持直接调用摄像头实现实时画面监控。但是,我们可以通过前端技术和第三方库的支持来实现该功能。
以下是一个完整的案例代码,实现了在Django网页中调用摄像头实现实时画面监控,包括前后端代码:
前端代码(HTML和JavaScript):
<!DOCTYPE html>
<html>
<head>
<title>Camera Streaming Demo</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<video id="video" width="640" height="480" autoplay></video>
<script>
var video = document.getElementById("video");
if (navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({ video: true })
.then(function (stream) {
video.srcObject = stream;
})
.catch(function (error) {
console.log(error);
});
}
var timer = setInterval(function () {
var canvas = document.createElement('canvas');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
var data = canvas.toDataURL('image/jpeg');
$.ajax({
url: '/save_image',
method: 'POST',
data: {
image_data: data
},
success: function (response) {
console.log(response);
}
});
}, 1000);
</script>
</body>
</html>
后端代码(Python和Django):
# views.py
from django.shortcuts import render
from django.http import JsonResponse
def index(request):
return render(request, 'index.html')
def save_image(request):
if request.method == 'POST':
image_data = request.POST.get('image_data')
# 处理图像数据的代码
return JsonResponse({'success': True})
return JsonResponse({'success': False})
# urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index),
path('save_image', views.save_image),
]
阅读全文