1

I want to take a picture from a webcam and save it in ImageField. I've seen some results related to this question, but I'm not able to understand how they work. For example: How can I capture a picture from webcam and store it in a ImageField or FileField in Django? My HTML form

<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;
}

My 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)

As a matter of fact, I tried to understand all the code in the link, but somehow I could not achieve what I wanted to do. I would be very happy if you could help me with this. Thanks for your help.

1 Answers1

0

This code will not works in a server because you are trying to access the local temporary file generated by browser. So your browser generate the file and save on your disk - then the server find on server disk a file with same name on temporary file, that does not work. My suggestion is you use ajax to send the file to server route (please have a look on fetch for example or include jQuery on your project). Using fetch you can send a post request including the file and then save it on server disk/database/whatever you want.

Documentation of file upload in Django: https://docs.djangoproject.com/en/4.0/topics/http/file-uploads/

Fetch example sending a file: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#uploading_a_file

JQuery: https://api.jquery.com/jquery.ajax/