I'm working on a Django application where the user can trigger the webcam with javascript and snap a picture. This picture is stored in a canvas. I want to retrieve this image with python as a base64 string, convert that into a png file and save it into the Django server. This is my code so far
HTML Template
<center>
<button type="button" name="button" class='btn btn-outline-dark btn-lg' id='start'>Start Video Capture</button>
<div class="container-fluid mt-2">
<video id="video" width="640" height="480" autoplay></video><br>
<button type="button" data-toggle="modal" data-target="#image_model" class="btn btn-lg btn-dark" id="snap">Snap Photo</button>
</div>
</center>
<center>
<canvas id="canvas" width="640" height="480"></canvas>
</center>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Retake</button>
<form class="image_to_server" action="{% url 'img_submit' %}" method="post">
{% csrf_token %}
<input type="text" name="base64Field" value="" id='base64'>
<input type="submit" value="Use Image" class="btn btn-primary" id="use_image">
</form>
Javascript Code
// Grab elements, create settings, etc.
var video = document.getElementById('video');
// Elements for taking the snapshot
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
$('#start').click(function() {
// Get access to the camera!
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({
video: true
}).then(function(stream) {
//video.src = window.URL.createObjectURL(stream);
video.srcObject = stream;
video.play();
});
}
$('#snap').fadeIn();
// Trigger photo take
$('#snap').click(function() {
context.drawImage(video, 0, 0, 640, 480);
var dataURL = canvas.toDataURL();
$('#base64').val(dataURL)
$("#use_image").click(function() {
console.log('clicked');
});
});
});
Django views.py
def img_submit(request):
if request.method == 'POST':
data = request.POST.get('base64Field')
byte_data = base64.b64decode(data)
image_data = BytesIO(byte_data)
img = Image.open(image_data)
return HttpResponse(data)
I am getting an "incorrect padding error" for the python code. I am not sure what I am doing wrong. Or how to rectify this error.
I followed this link to write the python code.