2017-10-21 22 views
0

私はpythonを使い慣れています。私は自分のウェブカメラからhtmlとAJAX javascriptそれをサーバー側のPythonに保存します。私は、クライアント側のHTMLを使用して画像のキャプチャを完了しましたが、保存する方法とHTML側のクライアント側からサーバー側のpython.ifにデータを渡す方法を知らない誰も私に助けてくださいしてください... ありがとうございました... My.html:クライアントサイド(html)から写真を撮ってサーバー側(Python)に保存するには

<!doctype html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <title>Get User Media - Photo</title> 
</head> 
<body> 
<button id="take">Take a photo</button><br /> 
<video id="v"></video> 
<canvas id="canvas" style="display:none;"></canvas> 

<img src="D:/VoteTest/img.jpg" id="photo" alt="photo"> 
<script> 
    ;(function(){ 
     function userMedia(){ 
      return navigator.getUserMedia = navigator.getUserMedia || 
      navigator.webkitGetUserMedia || 
      navigator.mozGetUserMedia || 
      navigator.msGetUserMedia || null; 

     } 


     // Now we can use it 
     if(userMedia()){ 
      var videoPlaying = false; 
      var constraints = { 
       video: true, 
       audio:false 
      }; 
      var video = document.getElementById('v'); 

      var media = navigator.getUserMedia(constraints, function(stream){ 

       // URL Object is different in WebKit 
       var url = window.URL || window.webkitURL; 

       // create the url and set the source of the video element 
       video.src = url ? url.createObjectURL(stream) : stream; 

       // Start the video 
       video.play(); 
       videoPlaying = true; 
      }, function(error){ 
       console.log("ERROR"); 
       console.log(error); 
      }); 


      // Listen for user click on the "take a photo" button 
      document.getElementById('take').addEventListener('click', function(){ 
       if (videoPlaying){ 
        var canvas = document.getElementById('canvas'); 
        canvas.width = video.videoWidth; 
        canvas.height = video.videoHeight; 
        canvas.getContext('2d').drawImage(video, 0, 0); 
        var data = canvas.toDataURL('image/webp'); 
        document.getElementById('photo').setAttribute('src', data); 
       } 
      }, false); 



     } else { 
      console.log("KO"); 
     } 
    })(); 
</script> 
</body> 
</html> 

答えて

1

私はプロジェクトのために、最近、これをしませんでした。あなたは、フォームデータ内の画像を送信するためにXHRを使用することができます。

let formdata = new FormData(); 
formdata.append("image", data); 
let xhr = new XMLHttpRequest(); 
xhr.open('POST', 'http://yourserver/image', true); 
xhr.onload = function() { 
    if (this.status === 200) 
     console.log(this.response); 
    else 
     console.error(xhr); 
}; 
xhr.send(formdata); 

私はトラブルキャンバスを変換するtoDataURLを使用していたので、私は簡単に変換するためにtoBlobを使用:ここで

canvas.toBlob(callBackToMyPostFunctionAbove, 'image/jpeg'); 

はサンプルですJavaScriptとPythonサーバーが組み込まれたHTMLファイル。

HTML &埋め込まれたJavaScript

JavaScriptが使用しています:

  1. getUserMediaをローカルビデオストリーム
  2. に画像キャプチャ
  3. キャンバスを開始するための画像上でのマウスクリックを開始しますgetUserMediaストリームから画像を保存するオブジェクト
  4. これは任意のエラーチェックすることなく、異なるブラウザでgetUserMediaをポリフィルするadapter.jsを使用

    <!DOCTYPE html> 
    <html> 
    <head> 
        <title>Post an Image test</title> 
        <script src="https://webrtc.github.io/adapter/adapter-latest.js"></script> 
    </head> 
    <style> 
        /* mirror the image */ 
        video, canvas { 
        transform: scale(-1, 1); /*For Firefox (& IE) */ 
        -webkit-transform: scale(-1, 1); /*for Chrome & Opera (& Safari) */ 
    } 
    </style> 
    <body> 
    <video id="myVideo" autoplay></video> 
    
    <script> 
    
        let v = document.getElementById("myVideo"); 
    
        //create a canvas to grab an image for upload 
        let imageCanvas = document.createElement('canvas'); 
        let imageCtx = imageCanvas.getContext("2d"); 
    
        //Add file blob to a form and post 
        function postFile(file) { 
         let formdata = new FormData(); 
         formdata.append("image", file); 
         let xhr = new XMLHttpRequest(); 
         xhr.open('POST', 'http://localhost:5000/image', true); 
         xhr.onload = function() { 
          if (this.status === 200) 
           console.log(this.response); 
          else 
           console.error(xhr); 
         }; 
         xhr.send(formdata); 
        } 
    
        //Get the image from the canvas 
        function sendImagefromCanvas() { 
    
         //Make sure the canvas is set to the current video size 
         imageCanvas.width = v.videoWidth; 
         imageCanvas.height = v.videoHeight; 
    
         imageCtx.drawImage(v, 0, 0, v.videoWidth, v.videoHeight); 
    
         //Convert the canvas to blob and post the file 
         imageCanvas.toBlob(postFile, 'image/jpeg'); 
        } 
    
        //Take a picture on click 
        v.onclick = function() { 
         console.log('click'); 
         sendImagefromCanvas(); 
        }; 
    
        window.onload = function() { 
    
         //Get camera video 
         navigator.mediaDevices.getUserMedia({video: {width: 1280, height: 720}, audio: false}) 
          .then(stream => { 
           v.srcObject = stream; 
          }) 
          .catch(err => { 
           console.log('navigator.getUserMedia error: ', err) 
          }); 
    
        }; 
    
    </script> 
    </body> 
    </html> 
    

をフォームデータとしてコードファイルを送信する。

Pythonのサーバー

そして、ここでは、Webサーバーとしてフラスコを使用してPythonでのサンプルです:

from flask import Flask, request, Response 
import time 

PATH_TO_TEST_IMAGES_DIR = './images' 

app = Flask(__name__) 

@app.route('/') 
def index(): 
    return Response(open('./static/getImage.html').read(), mimetype="text/html") 

# save the image as a picture 
@app.route('/image', methods=['POST']) 
def image(): 

    i = request.files['image'] # get the image 
    f = ('%s.jpeg' % time.strftime("%Y%m%d-%H%M%S")) 
    i.save('%s/%s' % (PATH_TO_TEST_IMAGES_DIR, f)) 

    return Response("%s saved" % f) 

if __name__ == '__main__': 
    app.run(debug=True, host='0.0.0.0') 
関連する問題