Как я могу захватить изображение с веб-камеры и сохранить его в ImageField в Django?
Я хочу сделать снимок с веб-камеры и сохранить его в ImageField. Я видел некоторые результаты, связанные с этим вопросом, но я не могу понять, как они работают. Например: Как я могу получить картинку с веб-камеры и сохранить ее в ImageField или FileField в Django? . Моя HTML форма
<div class="contentarea">
<div class="Input">
<form method="POST" name="inputForm" enctype='multipart/form-data'>
{% csrf_token %}
<div id="camera" class="camera">
<video id="video">Video stream not available.</video>
<button id="startbutton" type="button">Take photo</button>
<input id="webimg" value="" name="src" type="text" style="display: none;">
<canvas id="canvas">
</canvas>
</div>
<br>
<div>
<img id="photo" alt="your image">
</div>
<br>
<button type="submit" class="btn btn-outline-warning" id="submit">Save</button>
</form>
</div>
<img src="{{ path }}" alt="The screen capture will appear in this box.">
Javascript
(function() {
var width = 320;
var height = 0;
var streaming = false;
var video = null;
var canvas = null;
var photo = null;
var startbutton = null;
function startup() {
video = document.getElementById('video');
canvas = document.getElementById('canvas');
photo = document.getElementById('photo');
startbutton = document.getElementById('startbutton');
navigator.mediaDevices.getUserMedia({video: true, audio: false})
.then(function(stream) {
video.srcObject = stream;
video.play();
})
.catch(function(err) {
console.log("An error occurred: " + err);
});
video.addEventListener('canplay', function(ev){
if (!streaming) {
height = video.videoHeight / (video.videoWidth/width);
if (isNaN(height)) {
height = width / (4/3);
}
video.setAttribute('width', width);
video.setAttribute('height', height);
canvas.setAttribute('width', width);
canvas.setAttribute('height', height);
streaming = true;
}
}, false);
startbutton.addEventListener('click', function(ev){
takepicture();
ev.preventDefault();
}, false);
clearphoto();
}
function clearphoto() {
var context = canvas.getContext('2d');
context.fillStyle = "#AAA";
context.fillRect(0, 0, canvas.width, canvas.height);
var data = canvas.toDataURL('image/png');
photo.setAttribute('src', data);
}
function takepicture() {
var context = canvas.getContext('2d');
if (width && height) {
canvas.width = width;
canvas.height = height;
context.drawImage(video, 0, 0, width, height);
var data = canvas.toDataURL('image/png');
photo.setAttribute('src', data);
} else {
clearphoto();
}
}
window.addEventListener('load', startup, false);
})();
CSS
#video {
border: 1px solid black;
box-shadow: 2px 2px 3px black;
width:320px;
height:240px;
}
#photo {
border: 1px solid black;
box-shadow: 2px 2px 3px black;
width:320px;
height:240px;
}
#canvas {
display:none;
}
.camera {
width: 340px;
display:inline-block;
}
.output {
width: 340px;
display:inline-block;
}
#startbutton {
display:block;
position:relative;
margin-left:auto;
margin-right:auto;
bottom:32px;
background-color: rgba(0, 150, 0, 0.5);
border: 1px solid rgba(255, 255, 255, 0.7);
box-shadow: 0px 0px 1px 2px rgba(0, 0, 0, 0.2);
font-size: 14px;
font-family: "Lucida Grande", "Arial", sans-serif;
color: rgba(255, 255, 255, 1.0);
}
.contentarea {
font-size: 16px;
font-family: "Lucida Grande", "Arial", sans-serif;
width: 760px;
}
Мой Views.py
@login_required(login_url='accounts:login')
def image_upload(request, slug):
return_obj = get_object_or_404(Return, slug=slug)
if request.method == 'POST' :
path = request.POST["src"]
image = NamedTemporaryFile()
image.write(urlopen(path).read())
image.flush()
image = File(image)
name = str(image.name).split('\\')[-1]
name += '.jpg'
image.name = name
obj = ReturnImage.objects.create(image=image,slug=return_obj.slug)
obj.save()
return redirect("return_module:index")
context = {
'returnn': returnn,
}
return render(request,"return/image_upload.html",context)
Собственно говоря, я пытался понять весь код в ссылке, но почему-то не смог добиться того, что хотел сделать. Я был бы очень рад, если бы вы помогли мне с этим. Спасибо за помощь.
Этот код не будет работать на сервере, потому что вы пытаетесь получить доступ к локальному временному файлу, сгенерированному браузером. То есть ваш браузер генерирует файл и сохраняет его на вашем диске - затем сервер находит на диске сервера файл с тем же именем во временном файле, что не работает.
Я предлагаю использовать ajax
для отправки файла на серверный маршрут (пожалуйста, посмотрите на fetch
для примера или включите jQuery в ваш проект). Используя fetch
, вы можете послать пост-запрос, включающий файл, а затем сохранить его на диске сервера/базе данных/как угодно.
Документирование загрузки файлов в Django: https://docs.djangoproject.com/en/4.0/topics/http/file-uploads/
Пример отправки файла: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#uploading_a_file