我正在开发一个Django应用程序,用户可以在其中使用javascript触发网络摄像头并拍摄图片。此图片存储在画布中。我想使用python作为base64字符串来检索此图像,将其转换为png文件并将其保存到Django服务器中。到目前为止,这是我的代码
HTML模板
<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代码
// 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)
我收到python代码的“错误填充错误”。我不确定自己在做什么错。或如何纠正此错误。
我遵循此link编写了python代码。
答案 0 :(得分:1)
您没有从字符串中删除标头,这意味着它不仅是b64数据
如果您查看示例,将会看到以下几行
import re
base64_data = re.sub('^data:image/.+;base64,', '', data)
删除标题后,您应该可以将字符串用作b64
即时消息所涉及的标题如下data:image/png;base64,