Home » Php » javascript – Uploading canvas image to server written in Python

javascript – Uploading canvas image to server written in Python

Posted by: admin February 25, 2020 Leave a comment

Questions:

Hi Im doing a demo facial recognition project which uses a server written in Python. The server does facial recognition and return the uploaded image by drawing a box around the face inside the image. I’m using WebRTC to capture image and then upload the canvas image, but I can’t get it to work. Previously, I used input=”file” to upload the image to the server through form with method=”POST”, which worked flawlessly, but now the WebRTC approach isn’t working in my favor. I’ve searched several posts but to no avail and this is the code I am currently using which is to convert the image data in base64 to image. I still can’t figure out why….

PHP

<?php
$img = $_POST['img'];
$img = str_replace('data:image/jpeg;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = $_SERVER['DOCUMENT_ROOT'] . '/images/some_name.png';
file_put_contents($file, $data);                      
?>

JavaScript

 function takepicture() {
 var context = canvas.getContext('2d');
 if (width && height) {
  canvas.width = width;
  canvas.height = height;
  context.drawImage(video, 0, 0, width, height);
   $.post('/ajax/uploadthumbnail',
{
   id : id,
   data: data,
   img: canvas.toDataURL('image/jpeg')
}, function(data) {
     console.log(data);
});
  var data = canvas.toDataURL('image/jpeg');
  photo.setAttribute('src', data);

} else {
  clearphoto();
}

}

HTML

        <form method="POST" form class="login100-form validate-form" enctype="multipart/form-data" action="" onsubmit="prepareImg();">
        <div class="wrap-input100 validate-input" data-validate = "Enter e-mail">
                        <input class="input100" type="text" name="staff_email" placeholder="E-mail">
                            <span class="focus-input100" data-placeholder=""></span>
                </div>
        <div class="camera">
            <video id="video">Video stream not available.</video>
            <button id="startbutton">Take photo</button> 
        </div>
                <canvas id="canvas">
        </canvas>
        <div class="output">
            <img id="photo" alt="The screen capture will appear in this box.">

Am I missing something? I really need some guidance, I’ll upvote as many answers as possible !!!! I’m in desperate need for help! THANKS IN ADVANCE

How to&Answers: