2

I am using the following code to use a device camera to capture an image, a still photo and show it in the browser. It is working fine but what I would like to do is store the image with a unique number into a website folder and store a link to it in a database. So my question is how do I grab the image data with js and store it in a folder with a reference number. Would be very grateful for any help.

<html>
<body>
    <video id="video" width="640" height="480" autoplay></video>
    <button id="snap">Take Photo</button>
    <canvas id="canvas" width="640" height="480"></canvas>
    <script>
        let canvas = document.querySelector("#canvas");
let context = canvas.getContext("2d");
let video = document.querySelector("#video");
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia){
    navigator.mediaDevices.getUserMedia({video: true}).then((stream) =>{
       video.srcObject = stream;
       video.play();
    });
}
document.getElementById("snap").addEventListener("click", () => {
    context.drawImage(video, 0, 0, 640, 480); 
 });

    </script>
</body>
</html>

I have found following code but needs manual click to download and selcet a folder'

function downloadCanvas(){  
    // get canvas data  
    var image = canvas.toDataURL();  
  
    // create temporary link  
    var tmpLink = document.createElement( 'a' );  
    tmpLink.download = 'image.png'; // set the name of the download file 
    tmpLink.href = image;  
  
    // temporarily add link to body and initiate the download  
    document.body.appendChild( tmpLink );  
    tmpLink.click();  
    document.body.removeChild( tmpLink );  
}
<button onclick="downloadCanvas()">Download Phot!</button>

I really wanted it to automatically save the image to the site folder for say photos.

  • use the device captured image to a particular folder in a particular location. use this location to find the images and a dynamically populate them on the site in the server – Hari Kishore Aug 07 '21 at 10:51
  • @kishore Thanks for your input Kishore, any idea on how to get the image from canvas into site folder? –  Aug 07 '21 at 16:38
  • Got your question now, when you added the codes. `Canvas` can generally confuse with other languages tools, like gui canvas in c#, java etc. – Hari Kishore Aug 08 '21 at 06:36

2 Answers2

1

I will be telling you the approach i took and came to a result. To save a file we should look into how browser interacts with native file systems.

Approach 1

Find if browser provide any such apis to directly do that? like

OS.File.writeFile(writePath, file)

As far as I could research, I found that for chrome it doesn't provides an API to deal with native storage. have a look here.

Approach 2

Can we right click the image using JS i.e., the context menu on the image, and click save image as? In short answer was no. (tried using chrome.downloads.download)

Approach 3

Can we download generated images? That would resolve the issue. You may refer my answer here.

PFA the working code for that. Using canvas.toBlob() method to convert it to Blob image and then convert to ObjectURL using URL.createObjectURL(blob); and download image using that URL.

<html>
<body>
  <video id="video" width="640" height="480" autoplay></video>
  <button id="snap">Take Photo</button>
  <canvas id="canvas" width="640" height="480"></canvas>
  <script>
      let canvas = document.querySelector("#canvas");
let context = canvas.getContext("2d");
let video = document.querySelector("#video");
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia){
  navigator.mediaDevices.getUserMedia({video: true}).then((stream) =>{
     video.srcObject = stream;
     video.play();
  });
}
document.getElementById("snap").addEventListener("click", () => {
  context.drawImage(video, 0, 0, 640, 480); 

  canvas.toBlob(function(blob){
    console.log(typeof(blob))
    var blobUrl = URL.createObjectURL(blob);
    var link = document.createElement("a"); 
    link.href = blobUrl;
    link.download = "image.jpg";
    link.innerHTML = "Click here to download the file";
    document.body.appendChild(link); 
    document.querySelector('a').click() 
  }, 'image/jpeg', 1); 

});


  </script>
</body>
</html>
Hari Kishore
  • 2,201
  • 2
  • 19
  • 28
  • if I could adapt your code to include a php function like this it would be perfect. $data = $_POST['photo'];list($type, $data) = explode(';', $data);list(, $data) = explode(',', $data);$data = base64_decode($data);mkdir($_SERVER['DOCUMENT_ROOT'] . "/photos");file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/photos/".time().'.png', $data); How would that be possible –  Aug 10 '21 at 08:33
  • will look into that once i get some time, if you want can put code in github and share link, will go through and suggest you. (p.s. not very easy to go through codes here, or may be you just add another question with full fledged MarkDown, and give link) – Hari Kishore Aug 10 '21 at 08:42
  • Here is the link to the new question:[link](https://stackoverflow.com/questions/68738108/how-to-correct-code-not-giving-expected-results?noredirect=1#comment121480311_68738108) –  Aug 11 '21 at 08:29
1

A minimal Code would be,

document.getElementById("snap").addEventListener("click", () => {
        context.drawImage(video, 0, 0, 640, 480); 

        let blobUrl = canvas.toDataURL()
        let link = document.createElement("a"); 
          link.href = blobUrl;
          console.log(link)
          link.download = "image.jpg";
          link.innerHTML = "Click here to download the file";
          document.body.appendChild(link); 
          document.querySelector('a').click() 
      });

But above code gives you flexibility to add mime-type, you can specify image as jpeg or png (default) or web-format.

Also, instead of extension jpeg, you can give .txt if you want to store the base64 format of your image.

Additional read: Here

The files would be downloaded into default download location of browser. You can either change the download location to your desired location or can write an OS script ( either in batch or bash) to move the image files to servers file location.

Please comment if any further questions.

Hari Kishore
  • 2,201
  • 2
  • 19
  • 28
  • 1
    @ Kishore, thank you very much for the time and effort you put into your answers, I achieved a similar result with the above edited code: This also gives the option to manually click a download button and select a folder to manually select a download folder location. I really wanted it to automatically save the image to the site folder for say photos. But my research indicates this is not possible due to security reasons. So, it looks like I will have to re-think how I am using the device camera. Once again, very many thanks for your help and input, it’s very much appreciated. –  Aug 08 '21 at 10:18
  • one thing I just thought of, while looking back at my answer, you may try to give a shot using FileZilla. – Hari Kishore Jan 21 '22 at 17:26