简体   繁体   中英

How to save a photo using jQuery?

I am developing a software using html, javascript and php. It is supposed to save pictures using a webcam and then saving them into a database.

The thing is, it takes the pictures with no problem, but I actually can't figure out how to save the pictures to a file, and which format would be more efficient to save it into the MySql DB.

Here's how I am taking the pictures:

jQuery(document).ready(function(){
     //Este objeto guardará algunos datos sobre la cámara
     window.datosVideo = {
     'StreamVideo': null,
     'url' : null
     };
     jQuery('#botonFoto').on('click', function(e){
          var oCamara,
          oFoto,
          oContexto,
          w, h;

          oCamara = jQuery('#videoElement');
          oFoto = jQuery('#foto');
          w = oCamara.width();
          h = oCamara.height();
          oFoto.attr({'width': w, 'height': h});
          oContexto = oFoto[0].getContext('2d');
          oContexto.drawImage(oCamara[0], 0, 0, w, h);
           });
} );

The code takes the picture and draws it in the variable, which is a canvas

It can be done by the following procedure:

HTML:

<canvas id="foto"></canvas>
<form action="upload.php" method="POST" enctype="multipart/form-data">
    <input type="hidden" name="img" id="img_val">
    <input type="submit" name="submit" value="submit" />
</form>

JS:

 <script type="text/javascript">
    var c = document.getElementById("foto");
    document.getElementById("img_val").value = c.toDataURL();
 </script>

PHP:

<?php 
    if(isset($_POST['submit'])) : 
        $data = $_POST['img'];

        list($type, $data) = explode(';', $data);
        list(, $data)      = explode(',', $data);
        $data = base64_decode($data);

        file_put_contents('uploads/image.png', $data); 

    endif; 
?>

What's going here?

Firstly I added a form below the canvas to store image in base64 encoded format in a hidden input field.

Secondly JS script get content from canvas and stores it in base64 encoded format into the hidden input field.

Now when the user submits the form to upload image the data will be send to the server containing image in encoded format.

Thirdly PHP code remove the data:image/png;base64, and decode back the recieved data to store image with proper content into the server.

It may be helpful to you to understand how to send an image to the server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM