【问题标题】:How to capture an image and save from webcam using grails?如何使用 grails 从网络摄像头捕获图像并保存?
【发布时间】:2015-09-01 14:13:10
【问题描述】:

试图从网络摄像头捕捉图像并希望保存在驱动器上

使用 Grails 2.3.7

脚本代码

var video = document.querySelector("#videoElement");
var imageW;
                //check for getUserMedia support
                navigator.getUserMedia = navigator.getUserMedia
                        || navigator.webkitGetUserMedia
                        || navigator.mozGetUserMedia
                        || navigator.msGetUserMedia || navigator.oGetUserMedia;

                if (navigator.getUserMedia) {
                    // get webcam feed if available
                    navigator.getUserMedia({
                        video : true
                    }, handleVideo, videoError);
                }

                function handleVideo(stream) {

                    video.src = window.URL.createObjectURL(stream);
                }

                function videoError(e) {

                }
                var v, canvas, context, w, h;
                var imgtag = document.getElementById('imgtag'); 
                var sel = document.getElementById('"avatar"'); 

                document.addEventListener('DOMContentLoaded', function() {

                    v = document.getElementById('videoElement');
                    canvas = document.getElementById('canvas');
                    context = canvas.getContext('2d');
                    w = canvas.width;
                    h = canvas.height;

                }, false);

                function draw(v, c, w, h) {

                    if (v.paused || v.ended)
                        return false; // if no video, exit here

                    context.drawImage(v, 0, 0, w, h); // draw video feed to canvas

                    var uri = canvas.toDataURL("image/png"); // convert canvas to data URI


                      imageW = canvas.toDataURL("image/png");
        imageW = imageW.replace('data:image/png;base64,', '');


                    imgtag.src = uri;
                }

                document.getElementById('save').addEventListener('click',
                        function(e) {

                            draw(v, context, w, h); 

                        });


                var fr;

                sel.addEventListener('change', function(e) {
                    var f = sel.files[0]; 

                    fr = new FileReader();
                    fr.onload = receivedData; 

                    fr.readAsDataURL(f); 
                })

                function receivedData() {

                    imgtag.src = fr.result;
                }
                function webImageSubmit() {

                    alert(imageW);

                    var pars = "id=" + $('#id').val() + "&imageW=" + imageW;
                    $.ajax({
                        type : 'POST',
                        url : '/controller_name/saveWebCamImage',
                        data : pars,
                        error : function(request, status, error) {

                            document.getElementById('load').style.visibility = "hidden";
                        },
                        beforeSend : function() {
                            document.getElementById('load').style.visibility = "visible";
                        },
                        success : function(data) {
                            location.reload();
                        }
                    });
                }

控制器端:

def encodedData = javax.xml.bind.DatatypeConverter.parseBase64Binary(params.imageW.toString());
    def defaultPath = "/images/userImages";
        def webRootDir = servletContext.getRealPath("/");
        def systemDir = new File(webRootDir, defaultPath);
        if (!systemDir.exists()) {
            systemDir.mkdirs();
        }

        String file_name = "webImage.jpg";
        def csvFileDir = new File( systemDir, file_name);
        new File(systemDir, file_name).withOutputStream {
            it.write(encodedData);
          };

但是图像没有保存在驱动器上。

请帮帮我.. 谢谢。。

【问题讨论】:

  • 为什么要创建csvFileDir 对象?我没有看到它被使用。变量systemDir 中的完整路径是什么?您确认encodedData 包含数据了吗?运行 webapp 的操作系统用户帐户是否具有对 systemDir 的写入权限?
  • 用于将图像保存在本地驱动器上。
  • 好的...剩下的三个问题呢?

标签: javascript grails webcam-capture


【解决方案1】:

捕获和下载的完整代码

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
   const vid = document.querySelector('video');
navigator.mediaDevices.getUserMedia({video: true}) // request cam
.then(stream => {
  vid.srcObject = stream; // don't use createObjectURL(MediaStream)
  return vid.play(); // returns a Promise
})
.then(()=>{ // enable the button
  const btn = document.querySelector('button');
  btn.disabled = false;
  btn.onclick = e => {
    takeASnap()
    .then(download);
  };
});

function takeASnap(){
  const canvas = document.createElement('canvas'); // create a canvas
  const ctx = canvas.getContext('2d'); // get its context
  canvas.width = vid.videoWidth; // set its size to the one of the video
  canvas.height = vid.videoHeight;
  ctx.drawImage(vid, 0,0); // the video
  return new Promise((res, rej)=>{
    canvas.toBlob(res, 'image/jpeg'); // request a Blob from the canvas
  });
}
function download(blob){
  // uses the <a download> to download a Blob
  let a = document.createElement('a'); 
  a.href = URL.createObjectURL(blob);
  a.download = 'screenshot.jpg';
  document.body.appendChild(a);
  a.click();
}
});
</script>
</head>
<body>
<button disabled>
  take a snapshot</button>
<video></video>

</body>
</html>

【讨论】:

    【解决方案2】:

    完整的代码记录和下载

    <!DOCTYPE html>
    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    </head>
    <body>
    <button disabled>start recording</button>
    <video></video>
    <script>
    const vid = document.querySelector('video');
    navigator.mediaDevices.getUserMedia({video: true}) // request cam
    .then(stream => {
      vid.srcObject = stream; // don't use createObjectURL(MediaStream)
      return vid.play(); // returns a Promise
    })
    .then(()=>{ // enable the button
      const btn = document.querySelector('button');
      btn.disabled = false;
      btn.onclick = startRecording;
    });
    
    function startRecording(){
      // switch button's behavior
      const btn = this;
      btn.textContent = 'stop recording';
      btn.onclick = stopRecording;
    
      const chunks = []; // here we will save all video data
      const rec = new MediaRecorder(vid.srcObject);
      // this event contains our data
      rec.ondataavailable = e => chunks.push(e.data);
      // when done, concatenate our chunks in a single Blob
      rec.onstop = e => download(new Blob(chunks));
      rec.start();
      function stopRecording(){
        rec.stop();
        // switch button's behavior
        btn.textContent = 'start recording';
        btn.onclick = startRecording;
      }
    }
    function download(blob){
      // uses the <a download> to download a Blob
      let a = document.createElement('a'); 
      a.href = URL.createObjectURL(blob);
      a.download = 'recorded.webm';
      document.body.appendChild(a);
      a.click();
    }
    </script>
    </body>
    </html>
    

    【讨论】:

      【解决方案3】:

      预览捕获图像的代码

      <!doctype html>
      
      <html lang="en">
      <head>
          <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
          <title>WebcamJS Test Page</title>
          <style type="text/css">
              body { font-family: Helvetica, sans-serif; }
              h2, h3 { margin-top:0; }
              form { margin-top: 15px; }
              form input { margin-right: 15px; }
              #results { float:right; margin:20px; padding:20px; border:1px solid; background:#ccc; }
          </style>
      </head>
      <body>
          <div id="results">Your captured image will appear here...</div>
      
          <h1>WebcamJS Test Page</h1>
          <h3>Demonstrates 320x240 capture &amp; display with preview mode</h3>
      
          <div id="my_camera"></div>
      
          <!-- First, include the Webcam.js JavaScript Library -->
          <script type="text/javascript" src="webcam.min.js"></script>
      
          <!-- Configure a few settings and attach camera -->
          <script language="JavaScript">
              Webcam.set({
                  width: 320,
                  height: 240,
                  image_format: 'jpeg',
                  jpeg_quality: 90
              });
              Webcam.attach( '#my_camera' );
          </script>
      
          <!-- A button for taking snaps -->
          <form>
              <div id="pre_take_buttons">
                  <input type=button value="Take Snapshot" onClick="preview_snapshot()">
              </div>
              <div id="post_take_buttons" style="display:none">
                  <input type=button value="&lt; Take Another" onClick="cancel_preview()">
                  <input type=button value="Save Photo &gt;" onClick="save_photo()" style="font-weight:bold;">
              </div>
          </form>
      
          <!-- Code to handle taking the snapshot and displaying it locally -->
          <script language="JavaScript">
              function preview_snapshot() {
                  // freeze camera so user can preview pic
                  Webcam.freeze();
      
                  // swap button sets
                  document.getElementById('pre_take_buttons').style.display = 'none';
                  document.getElementById('post_take_buttons').style.display = '';
              }
      
              function cancel_preview() {
                  // cancel preview freeze and return to live camera feed
                  Webcam.unfreeze();
      
                  // swap buttons back
                  document.getElementById('pre_take_buttons').style.display = '';
                  document.getElementById('post_take_buttons').style.display = 'none';
              }
      
              function save_photo() {
                  // actually snap photo (from preview freeze) and display it
                  Webcam.snap( function(data_uri) {
                      // display results in page
                      document.getElementById('results').innerHTML = 
                          '<h2>Here is your image:</h2>' + 
                          '<img src="'+data_uri+'"/>';
      
                      // swap buttons back
                      document.getElementById('pre_take_buttons').style.display = '';
                      document.getElementById('post_take_buttons').style.display = 'none';
                  } );
              }
          </script>
      
      </body>
      </html>
      

      【讨论】:

        猜你喜欢
        • 2013-03-17
        • 2013-06-03
        • 2013-02-09
        • 2010-11-23
        • 1970-01-01
        • 1970-01-01
        • 2013-01-18
        相关资源
        最近更新 更多