How do i take picture from client side(html) and save it to server side(Python)

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

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

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

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

HTML & Embedded JavaScript

The JavaScript uses:

  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>

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

Python Server

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("https://stackoverflow.com/")
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")

Leave a Comment