自动从网络摄像头源拍摄照片,然后将其保存到文件,无需用户输入

问题描述 投票:0回答:2

我想在浏览器授予网络摄像头访问权限后自动从网络摄像头源拍摄照片,然后将其保存到文件中,无需用户输入。

我已经对图片捕捉进行了排序,但我不能:

A) 让它自动拍照

B) 保存图片

这个想法是,然后将输入用户电子邮件,然后图片文件将被重命名为他们的电子邮件。

这是我到目前为止所得到的:

<html>
<head>
  
</head>
<body>



<video id="player" controls autoplay></video>
<button id="capture">Capture</button>
<canvas id="canvas" width="320" height="240"></canvas>
<script>

  const player = document.getElementById('player');
  const canvas = document.getElementById('canvas');
  const context = canvas.getContext('2d');
  const captureButton = document.getElementById('capture');

  const constraints = {
    video: true,
  };

  captureButton.addEventListener('click', () => {
    // Draw the video frame to the canvas.
    context.drawImage(player, 0, 0, canvas.width, canvas.height);
  });

  // Attach the video stream to the video element and autoplay.
  navigator.mediaDevices.getUserMedia(constraints).then((stream) => {
    player.srcObject = stream;
  });
</script>

</html>

所以我只需要: A) 让它自动拍照 B) 保存图片

javascript html image video-capture capture
2个回答
-1
投票

您可以像普通函数一样调用对象的事件监听器。

在您的情况下,当您想要拍照时,只需在脚本中调用

captureButton.onclick()
即可。

对于下载文件,我建议使用 download.js (https://github.com/rndme/download)。您可以下载源代码,但如果您愿意,也可以通过一些 CDN 获取它。据我所知,download.js 只下载到“downloads”目录(至少在 Windows 上,苹果不确定)


-1
投票

根据您所写的内容,在未经用户同意的情况下实际拍照可能会存在一些道德问题,即使用户允许访问相机,也不意味着您可以立即拍照。

可能还有其他问题,例如,即使相机立即可用,并不意味着第一个图像流具有良好的图片框架,这意味着您可能需要等待一段时间直到框架准备好。

无论如何,我添加了另一个按钮,这样您就可以拍摄任意数量的照片,直到获得一张令您满意的照片为止。 第一张照片始终是自动拍摄的,但您可以通过单击“拍摄另一张照片”按钮来覆盖它。 这是完整的工作代码: <video id="player" controls autoplay></video> <canvas id="canvas" width="640" height="480" ></canvas> <!-- Input for user email --> <input type="text" id="userEmail" placeholder="Enter your email"> <button onclick="captureImage()">Take another Photo</button> <button onclick="downloadImage()">Download</button> <script> const player = document.getElementById('player'); const canvas = document.getElementById('canvas'); const context = canvas.getContext('2d'); const userEmailInput = document.getElementById('userEmail'); const constraints = { video: true, }; function captureImage() { context.drawImage(player, 0, 0, canvas.width, canvas.height); } function downloadImage() { const email = userEmailInput.value; if (!email) { alert('Please enter your email first.'); return; } const link = document.createElement('a'); canvas.toBlob(function(blob) { link.href = URL.createObjectURL(blob); link.download = email + '.png'; // naming the downloaded file with email link.click(); }, 'image/png'); } navigator.mediaDevices.getUserMedia(constraints).then((stream) => { player.srcObject = stream; // Once the webcam stream is loaded, capture the image player.onloadedmetadata = function(e) { captureImage(); }; }); </script>

© www.soinside.com 2019 - 2024. All rights reserved.