我如何从客户端拍摄照片(html)并将其保存到服务器端(Python) [英] How do i take picture from client side(html) and save it to server side(Python)

查看:92
本文介绍了我如何从客户端拍摄照片(html)并将其保存到服务器端(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的python我做了一个应用程序使用python,我想从我的摄像头使用html和AJAX javascript捕获图像并将其保存到服务器端python。我已经完成使用客户端HTML捕获图像,但我不知道如何保存并将数据从HTML客户端传递到服务器端python.If任何人这样做,请你能帮助我...
谢谢您提前...
My.html:

I'm new to python i did one application using python in that i want to capture Images from my webcam using html and AJAX javascript and save it to server side python. I have completed capturing of images from using client side HTML but i don't know how to save and pass the data from html client side to server side python.If anybody did this please can you help me... THANK YOU IN ADVANCE... My.html:

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


推荐答案

我刚刚为一个项目做了这个。您可以使用XHR在表单数据中发送图像:

I just did this recently for a project. You can use XHR to send the image inside form data:

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 进行更简单的转换:

I had trouble using the toDataURL to convert the canvas, so I used toBlob for an easier conversion:

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

这是一个嵌入式JavaScript和我的Python服务器的示例HTML文件。

Here is a sample HTML file with embedded JavaScript and my Python server.

HTML&嵌入式JavaScript

JavaScript使用:

The JavaScript uses:


  1. getUserMedia启动本地视频流

  2. 鼠标点击图片以启动图片捕获
  3. 画布对象从getUserMedia流中保存图片
  4. li>
  5. XHR 发送作为表单数据的文件

  1. getUserMedia to start a local video stream
  2. a mouse click on the image to initiate the image capture
  3. a canvas object to save an image from the getUserMedia stream
  4. XHR to send the file as form data

代码:

The code:

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

这会使用adapter.js在不同的浏览器上对getUserMedia进行填充​​,而不会进行任何错误检查。

This uses adapter.js to polyfill getUserMedia on different browsers without any error checks.

Python服务器

以下是使用Flask作为Web服务器的Python示例: p>

And here is a sample in Python using Flask as a web server:

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

这篇关于我如何从客户端拍摄照片(html)并将其保存到服务器端(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆