Javascript 从网络应用程序中的网络摄像头或移动摄像头拍摄照片

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35253777/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:29:33  来源:igfitidea点击:

Take picture from webcam or mobile camera in web applications

javascriptjqueryhtmlcamera

提问by ganesh

I'm developing a web application which browse and take pictures from local and also I want to capture images through the camera. Im using the following code and i can capture device camera.

我正在开发一个 Web 应用程序,它可以从本地浏览和拍照,而且我想通过相机捕捉图像。我使用以下代码,我可以捕获设备相机。

<input type="file" capture="camera" accept="image/*" id="cameraInput" name="cameraInput">

Now, I want to get the image and onchangeevent, convert to base64 and want to show in that page itself.

现在,我想获取图像和 onchangeevent,转换为 base64 并希望在该页面本身中显示。

Kindly help me guys!

请帮助我的家伙!

采纳答案by Henock Bongi

You can do it like this:

你可以这样做:

$('#cameraInput').on('change', function(e){
 $data = e.originalEvent.target.files[0];
  $reader = new FileReader();
  reader.onload = function(evt){
  $('#your_img_id').attr('src',evt.target.result);
  reader.readAsDataUrl($data);
}});

回答by Ana Houa

Miles Erickson and Henock Bongi, you need to take reader.readAsDataUrl($data); out of the onload function in order that the onload fire.

Miles Erickson 和 Henock Bongi,你需要带 reader.readAsDataUrl($data); 退出 onload 函数,以便 onload 触发。

If you don't want to use jQuery see below:

如果您不想使用 jQuery,请参见下文:

function readFile(file) {                                                       
    var reader = new FileReader();
    reader.onload = readSuccess;                                            
    function readSuccess(evt) {     
        document.getElementById("your_img_id").src = evt.target.result                   
    };
    reader.readAsDataURL(file);                                              
} 

document.getElementById('cameraInput').onchange = function(e) {
    readFile(e.srcElement.files[0]);
};