1

I am doing a project on web development and I have to take a snapshot using my webcam to upload the user's input image. I am using the Python Django 1.6.5 framework for the same.

I am able to gain access to the user's webcam and am able to take a snapshot and view it on the HTML page.(It is displayed in the form of a canvas in the HTML page.). This is the code to capture the image from the webcam in my HTML page.

I have given comments in the HTML page for better understanding.

<!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>

I used the capture attribute in the file input as I read here

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

and expected that the captured screenshot in the canvas would be taken in as the file input.

With this in mind, I created my forms.py and views.py

This is my 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

and my 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()

This function in views should ideally get the user-captured image and should save it to the specified location.

But what I observe is that uploadFile=save_filewc(request.FILES['imagewc']) line gives an error .

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

which obviously means that the data from the canvas is not going to the input type file.

What I understand is Django view needs input type "file" from the form as user input to upload it to server on form submission. (I have a clearer understanding of this since I has a similar problem sometime back and was able to solve it.)

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.

as has been stated in https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.FILES

So what is the way in which I can convert the canvas data (which holds my captured screenshot) from HTML and receive it in the views.py by storing it in a html file input? Please help. Stuck for sometime now. Thanks in advance :)

naiveDeveloper
  • 625
  • 2
  • 11
  • 28
  • did you solve your it please ? here is my problem , can you help with it https://stackoverflow.com/questions/69321252/how-to-capture-image-from-webcam-in-web-browser-model-formset-django – artiest Sep 25 '21 at 06:38

1 Answers1

1

"and expected that the captured screenshot in the canvas would be taken in as the file input." Unfortunately you have made an assumption which is not based on any evidence: currently your the code does not have a connection to how to make <canvas> content as the <form> submissions.

One way to make the data from canvas to your server (as there are alternatives)

  • Export <canvas> content as an image (use toDataUrl())

  • Submit this base64 encoded data to your server using an AJAX request

This have been addressed before in the question How to save a HTML5 Canvas as Image on a server - in this case you need to decode the base64 URL on the server-side:

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

Community
  • 1
  • 1
Mikko Ohtamaa
  • 82,057
  • 50
  • 264
  • 435
  • Thanks @mikko. That helped saving the image as a jpeg. Any ideas on now can I submit that image on form submit in the django server? I kind of need that desperately to complete my flow . – naiveDeveloper Aug 08 '14 at 05:40
  • 2
    I am prettu sure `` does not provide any kind of write access - it is read-only: https://developer.mozilla.org/en-US/docs/Web/API/FileList - However you can use ´FormData´ to emulate blob-populated form submissions in JavaScript code: https://developer.mozilla.org/en-US/docs/Web/API/FormData – Mikko Ohtamaa Aug 08 '14 at 09:35