上传并保存用户的摄像头在Django --canvas元件拍摄截图文件(upload and sav

2019-10-20 15:26发布

我做的web开发一个项目,我一直在使用我的摄像头上传用户的输入图像拍摄快照。 我使用了相同的Python的Django的1.6.5框架。

我能够访问用户的摄像头和我能拍摄快照,并查看它的HTML页面。(它显示在HTML页面画布的形式)。 这是捕获从网络摄像头图像在我的HTML页面的代码。

我已在HTML页面的评论为更好地理解。

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href ="/static/css/styles.css" type="text/css"/>
<title>Capture image </title>
</head>
<body>
<form id="webcamPageForm" method="POST" enctype="multipart/form-data" action="/tryonViewWC/{{frame.slug}}/">
{% csrf_token %}

<video id="vid" width="640" height="480" autoplay></video><!-- shows my video stream playing -->
<input type="file" id="imagewc" name="imagewc" onclick="snapshot();" accept="image/*" capture> <!-- opens my hard drive and expects input from hard drive-->
<canvas id="canvas" name="canvas" width="640" height="480" style="border:1px solid #d3d3d3;"></canvas><br> <!--captured image displayed here-->
<input type="submit" id="SubmitWebCam" name="SubmitWebCam"  class="myButton" value= "Done" style="display:none"><br><!-- on submit should send user-captured snapshot to views.py-->

<script type="text/javascript">

    var video = document.querySelector("#vid");
    var canvas = document.querySelector('#canvas');
    var ctx = canvas.getContext('2d');
    var localMediaStream = null;

    var onCameraFail = function (e) {
        console.log('Camera did not work.', e);
        };

    function snapshot() {  

        if (localMediaStream) {
            ctx.drawImage(video, 0, 0);   // This draws the captured image on the canvas
        }
         document.getElementById('SubmitWebCam').style.display="block";
    }

    navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;

    window.URL = window.URL || window.webkitURL;

    navigator.getUserMedia({video:true}, function (stream) {
        video.src = window.URL.createObjectURL(stream);
        video.play();
        localMediaStream = stream;
    }, onCameraFail);

</script>
</form>
</body>
</html>

我使用的capture attribute中输入的文件,因为我在这里读

http://www.html5rocks.com/en/tutorials/getusermedia/intro/#toc-screenshot和http://dev.w3.org/2009/dap/camera/#dfn-capture

并预计在画布上获取的截屏将采取在作为文件输入。

考虑到这一点,我创建了forms.pyviews.py

这是我的forms.py

from django import forms

class ImageUploadWCForm(forms.Form):

    print("Image upload from WC form.")        
    imagewc = forms.ImageField(label='Select a file')              
    print "Hi in Webcam ", imagewc

而我views .py

def upload_webcam(request, frameslug):   

  print "in upload WBCAM "     
  if request.method == 'POST':
      form = ImageUploadWCForm(request.POST, request.FILES)
      #print "FILES", request.FILES

      if form.is_multipart():
          uploadFile=save_filewc(request.FILES['imagewc'])
          print('vALID iMAGE')
      else:
          print('Invalid image')

  else:
      form = ImageUploadWCForm()   

  return render_to_response('dummy.html')


def save_filewc(file, path=''):

  filename = "uploadedPicWC.jpg"
  fd = open('%s/%s' % (MEDIA_ROOT1, str(path) + str(filename)), 'wb')
  print "fd", fd
  print "str(path)",str(path)
  print "str(filename)",str(filename)
  for chunk in file.chunks():
      fd.write(chunk)
  fd.close()

此功能在意见应该得到最好的用户拍摄的图像,应该将其保存到指定的位置。

但我观察到的是, uploadFile=save_filewc(request.FILES['imagewc'])行给出了一个错误。

 Exception Type:    MultiValueDictKeyError
    Exception Value:    "'imagewc'"

这显然意味着,从画布中的数据不会输入类型文件。

我的理解是Django的视图需要输入型“文件”,从形式,用户输入把它上传到服务器上的表单提交。 (我对此有更清晰的认识,因为我也有类似问题的某个时候回来,能解决这个问题。)

HttpRequest.FILES
A dictionary-like object containing all uploaded files. Each key in FILES is the name from the <input type="file" name="" />. Each value in FILES is an UploadedFile.

如已经指出https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.FILES

那么,什么是我可以从HTML转换画布上的数据(持有我获取的截屏),并通过将其存储在一个HTML文件的输入接收它在views.py的方式吗? 请帮忙。 现在坚持了一段时间。 提前致谢 :)

Answer 1:

“和预期的是,在画布上获取的截屏将采取在作为文件输入”。 不幸的是你做这并非基于任何证据的假设:目前你的代码没有如何使一个连接<canvas>含量为<form>提交。

使从画布上的数据到你的服务器(因为有替代品)的一种方法

  • 出口<canvas>内容作为图像(使用toDataUrl()

  • 提交本base64编码数据使用AJAX请求服务器

这已经在面前的问题解决如何在HTML5画布保存为图片的服务器上 -在这种情况下,你需要解码的服务器端的base64网址:

https://stackoverflow.com/a/15376482/315168



文章来源: upload and save screenshot taken from users webcam in django --canvas element to file