【问题标题】:How can I capture a picture from webcam and store it in a ImageField or FileField in Django?如何从网络摄像头捕获图片并将其存储在 Django 的 ImageField 或 FileField 中?
【发布时间】:2021-09-08 19:54:10
【问题描述】:

我正在尝试从网络摄像头捕捉照片并将其存储在 FileField 或 ImageField 中。但我不知道如何根据要求获取捕获的图像数据。请检查我的 HTML 模板、javascript 代码和 views.py。任何人都可以建议一种方法来获取使用 javascript 捕获的图像数据,在 HTML 中提交表单吗?

class UserDetails(models.Model):
    User_name = models.CharField(max_length= 300)
    User_phone = models.BigIntegerField()
    User_address = models.TextField()
    User_pic = models.FileField(upload_to='documents/%Y/%m/%d')

我的 HTML 表单

{% extends 'base.html' %}
{% load static %}
{% block content %}  
 
<!DOCTYPE html>
<html lang="en">

<body class="">
 
      <div class="container-fluid">
        <div class="row">
         <div class="col-md-8">  
            <div id="accordion" role="tablist">

                <form method="POST" action="/usersave/" enctype="multipart/form-data">
                    {% csrf_token %}
                      ....

                   <div class="card-body">
                     <div class="row">
                       <div class="col-md-4 ml-auto mr-auto">
                          <div class="form-group">                                
                             <video id="video" autoplay ></video>                               
                             <canvas id="canvas"></canvas>                                
                       </div>
                 <button id="startbutton1" class="btn btn-outline-secondary btn-sm">Take Photo</button>
                              <script src="{% static "assets/js/capture.js" %}"></script> 
                            </div>

                            .....
                        <div class="img  pull-center" >                                            
                        <img id ="photo" name="photo" alt="The screen capture will appear in this box.">                   
              </form>
          </div>                
        </div>  
     </div>
  </div>

Views.py

def usersave(request):
if request.method== 'POST':        
    User_name = request.POST["Username"]
    User_phone = request.POST["Userphone"]
    User_address = request.POST["Useraddress"]
    pic = request.FILES["photo"]
    User_info= UserDetails(User_name=User_name, User_phone=User_phone, User_address=User_address, User_pic= pic)
    User_info.save()    
    return render(request, 'some.html')

使用这个 capture.js 文件,我可以拍照并在 img 标签中填充 HTML 文件

(function() {


    var width = 320;    
    var height = 0;    
    var streaming = false;  
    var video = null;
    var canvas = null;
    var photo = null;
    var startbutton1 = null;
  
    function startup() {
      video = document.getElementById('video');
      canvas = document.getElementById('canvas');
      photo = document.getElementById('photo');
      startbutton1 = document.getElementById('startbutton1');
  
      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);
  
      startbutton1.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);
  })();

【问题讨论】:

    标签: javascript python html django django-templates


    【解决方案1】:

    在您的表单中,img 只是在 &lt;img&gt; 标记中,它需要在 input

    请参阅answer 了解如何将 DataUrl 转换为表单输入

    <input type="hidden" name="photo" id="photo" />
    

    您的照片应在上述输入中。

    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');
             
            // Set the form value to data here
    
            photo.setAttribute('src', data);
          } else {
            clearphoto();
          }
        }
    

    【讨论】:

      【解决方案2】:

      我知道 Javascript 和 Django 之间很难通信,我们应该使用 Ajax 或 jQuery 请求。但是对于这个问题,我找到了一种方法,将网络摄像头的图像数据获取到后端(Django)。

      当用户拍摄照片时,照片会存储在本地临时文件夹中。我们可以用捕获到的图片URL数据来设置HTML中图片元素的src属性,即temp文件夹中图片的URL。

      现在,当用户点击提交按钮时,图片的 src 将出现在 post 请求中。由于 src 在 temp 文件夹中具有捕获图像的 URL 路径,因此我们可以读取它并将其存储在我们的模型中。下面的代码是示例。

      在我的views.py中,我可以添加

      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 = Image.objects.create(image=image)
      obj.save()
      

      其余代码与问题中发布的相同,包括 Javascript 和 HTML 代码。

      【讨论】:

        猜你喜欢
        • 2013-03-17
        • 1970-01-01
        • 2012-11-15
        • 2013-02-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多