【问题标题】:How can I get the size of the webcam image with getUserMedia?如何使用 getUserMedia 获取网络摄像头图像的大小?
【发布时间】:2012-12-24 17:53:39
【问题描述】:

我正在尝试找出我使用 getUserMedia 从网络摄像头获取的图像的大小。

现在,在我的 Macbook 中,我应该有一个 720p 相机,但我得到的图像是 640x480。不过,我假设情况并非总是如此,我希望能够处理尽可能多的相机。 (我更关心纵横比而不是尺寸本身,我只是想确保图片不会被拉伸)

可以这样做吗?

谢谢!
丹尼尔

【问题讨论】:

    标签: html webcam dimensions getusermedia


    【解决方案1】:

    您应该能够使用videoWidthvideoHeight 属性,如下所示:

    // Check camera stream is playing by getting its width
    video.addEventListener('playing', function() {
        if (this.videoWidth === 0) {
            console.error('videoWidth is 0. Camera not connected?');
        }
    }, false);
    

    更新:实际上,这在 Opera 中有效,但在 Chrome 中似乎不再受支持,并且尚未在 Firefox 中实现(至少不适用于视频流)。不过,它在 HTML5 spec 中,因此希望在这些浏览器的路线图上。

    更新 2:这确实有效,但要侦听的事件是“正在播放”而不是“播放”(已在上面的代码中修复)。当返回 play() 方法时会触发 "play" 事件,而实际开始播放时会触发 "playing" 事件。在 Opera、Chrome 和 Firefox 中测试。

    更新 3:Firefox 18 似乎反复触发“正在播放”事件,这意味着如果您在侦听器中执行大量代码,浏览器可能会停止运行。最好在触发后移除监听器,如下所示:

    var videoWidth, videoHeight;
    var getVideoSize = function() {
        videoWidth = video.videoWidth;
        videoHeight = video.videoHeight;
        video.removeEventListener('playing', getVideoSize, false);
    };
    
    video.addEventListener('playing', getVideoSize, false);
    

    【讨论】:

    • 是的,我看到了这个,但它不在 Chrome 或 Firefox 中......还有其他想法吗?谢谢!
    • 不怕。现在它已停止在 Chrome 中工作我正在寻找自己的解决方法。抱歉,我帮不上忙。
    • 知道了!经过一番试验,结果证明 videoWidth 属性仅在“播放”事件(而不是“播放”)被触发后才存在。更新了上面的答案以显示这一点。
    【解决方案2】:

    挂钩到playing 事件在 Firefox 中不起作用(至少在我使用的 Ubuntu 12.04 LTS 上的 Firefox 26.0 中)。 playing 事件在视频开始播放后触发一次或两次。当playing 事件触发时,videoWidthvideoHeight 要么为 0,要么为未定义。检测videoWidthvideoHeight 的更可靠方法是暂停和播放视频,这似乎总是有效。下面的代码 sn-p 对我有用:

    //Detect camera resolution using pause/play loop.
    var retryCount = 0;
    var retryLimit = 25;
    var video = $('.video')[0]; //Using jquery to get the video element.
    video.onplaying = function(e) {
        var videoWidth = this.videoWidth;
        var videoHeight = this.videoHeight;
        if (!videoWidth || !videoHeight) {
            if (retryCount < retryLimit) {
                retryCount++;
                window.setTimeout(function() {
                    video.pause();
                    video.play();
                }, 100);
            }
            else {
                video.onplaying = undefined; //Remove event handler.
                console.log('Failed to detect camera resolution after ' + retryCount + ' retries. Giving up!');
            }
        }
        else {
            video.onplaying = undefined; //Remove event handler.
            console.log('Detected camera resolution in ' + retryCount + ' retries.');
            console.log('width:' + videoWidth + ', height:' + videoHeight);
        }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-24
      • 1970-01-01
      • 2018-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多