网络摄像头图像刷新与ajax

webcam image refresh with ajax

本文关键字:ajax 刷新 图像 摄像头 网络      更新时间:2023-09-26

我有一个图像,正在不断从本地网络摄像头源更新,然后在网站上显示。我可以让图像显示,并通过刷新页面,图像将更新(显然)。

我想知道的是,我怎么能更新这个图像每(让我们说)5秒,而不必手动刷新页面(即。利用ajax)。

我不太确定的基本事情:

  1. <img src=""/> <—如何加载位于javascript代码中的图像url

  2. 在javascript代码中,我如何创建一个函数,将自动更新图像源,而不必重新加载页面

据我所知,在阅读周围,其中一个主要问题是浏览器将加载缓存的图像,除非每次产生的httprequest看起来不同,因此我需要在url字符串中添加一个额外的项目(即。www.yoursire.com?image=foo&date=bar(日期由日期函数或其他迭代值抓取)),以规避这种可怕的浏览器倾向?

提前感谢!

不写所有代码

  • 查看javascript函数setTimeout()setInterval()

  • 很容易修改一个元素的src属性

    document.getElementbyId("imageId").setAttribute("src", imageUrl);
    
  • 如果你的图像请求url是相同的每次(但pic已经改变了服务器端),你可以添加一个"无缓存"的ajax请求头,或可能添加一个随机查询字符串的图像强制每次重新加载(例如http://mydomain/myimage?3754854)

使用jQuery:

    $(document).ready(function() {
       window.setInterval("refreshCamera();", 1000); // one second interval
    });
    var url = 'http://www.x.com/abc?refresh=';
    var forcerefresh = 0;
    function refreshCamera()
    {
       forcerefresh = forcerefresh + 1;
       $('#myImageId').attr('src',url + forcerefresh);

}

(强制刷新是为了防止浏览器使用本地缓存的图像)

我已经这样做了,它使用设置图像源工作。同样在服务器端,您必须发送无缓存HTTP头以防止缓存。

<img src="" id="webcam" />
<script type="text/javascript">
var int=self.setInterval("reload()",1000);
function reload(){
   $("#webcam").attr("src", "/mysite/webcamImage");
}
</script>

您可以使用jquery加载一个图像对象,然后附加一个计时器并每5秒运行一次代码。

下面是一个例子:

// when the DOM is ready
$(function () {
  var img = new Image();
  // wrap our new image in jQuery, then:
  $(img)
    // once the image has loaded, execute this code
    .load(function () {
      // set the image hidden by default    
      $(this).hide();
      // with the holding div #loader, apply:
      $('#loader')
        // remove the loading class (so no background spinner), 
        .removeClass('loading')
        // then insert our image
        .append(this);
      // fade our image in to create a nice effect
      $(this).fadeIn();
    })
    // if there was an error loading the image, react accordingly
    .error(function () {
      // notify the user that the image could not be loaded
    })
    // *finally*, set the src attribute of the new image to our image
    .attr('src', 'images/headshot.jpg');
});

在这里阅读更多内容:

  • http://jqueryfordesigners.com/image-loading/

关于防止缓存动态加载的图像,你可以在url中添加最后修改的时间戳:

<img src="image.jpg?lastmodified=1291235678" ...

我也有同样的需要,所以我在下面附加了我自己的js解决方案。有时候,当ajax刷新发生时,我们的网络摄像头会在将jpg写入目录的过程中,所以我不会显示破碎的图像,而是呈现一个动画gif。

JS:

<script>
$(document).ready(function () {
    (function () {
        // show webcam jpg on initial page load
        var refreshWebcam = function () {
            // webcam link is appended with a timestamp to prevent caching
            var webcamImg = 'http://abs_path_to_webcam_img/webcam1.jpg' + '?' + (new Date()).getTime();
            var loadingImg = 'http://abs_path_to_webcam_loading_img.gif'
            $.ajax({
                url: webcamImg,
                type: 'HEAD',
                error: function () {
                    $('#refresh').attr('src', loadingImg);
                    //console.log('failed loading ' + webcamImg);
                    // if there's an error, retry loading image every half second
                    setTimeout(function () {
                        refreshWebcam();
                    }, 500)
                },
                success: function () {
                    $('#refresh').attr('src', webcamImg);
                    //console.log('successfully loaded ' + webcamImg);
                }
            });
        };
        // refresh webcam jpg every 5 seconds
        window.setInterval(refreshWebcam, 5000);
        refreshWebcam();
    })();
});

<img alt="Web Camera Image" id="refresh" src="http://abs_path_to_webcam_loading_img.gif" /> 

如果它流行起来,禁用缓存会使你的摄像头不堪重负(即使是好的摄像头)

我尝试允许图像被允许缓存6秒(Cache-Control: max-age=6),因为我需要防止网络摄像头不堪重负。我正在使用的代码看起来有点像这样,但它有一个问题:

<img alt="Webcam image of something popular" id="liveimage" src="http://example.com/webcams/suddenlypopular.jpg" /><br />
<script type="text/javascript">
(function() {
    setInterval(function() {
        var myImageElement = document.getElementById('liveimage');
        myImageElement.src = 'http://example.com/webcams/suddenlypopular.jpg';
    }, 6000);
}());
</script>

之前,web开发人员使用了一个?rand=(随机数)作为缓存破坏技术。当图像是可缓存的(即使只是很短的一段时间),这是很糟糕的,因为这意味着你可能(取决于你的缓存是否将查询参数视为不可缓存),意味着你得到一个非常低的缓存命中率,你得到很多页面表示正在建立。

问题是图像现在不刷新,因为虽然src属性被重新分配,但它实际上并没有改变为不同的值,所以浏览器(Chrome 51)没有更新图像。我将逻辑更改为具有?1?2查询字符串参数,并在它们之间交替。

<img alt="Webcam image of something popular" id="liveimage" src="http://example.com/webcams/suddenlypopular.jpg?1" /><br />
<script type="text/javascript">
(function() {
    setInterval(function() {
        var myImageElement = document.getElementById('liveimage');
        if (myImageElement.src == 'http://example.com/webcams/suddenlypopular.jpg?1') {
            myImageElement.src = 'http://example.com/webcams/suddenlypopular.jpg?2';
        } else {
            myImageElement.src = 'http://example.com/webcams/suddenlypopular.jpg?1';
        }
        myLogElement.innerHTML = myImageElement.src;
    }, 6000);
}());
</script>

EDIT:虽然这在Chrome和IE中工作,但它在Firefox中不起作用,所以我提出了一个可在Chrome, Firefox和IE中工作的替代解决方案(Safari目前未经测试)。

<img alt="Webcam image of something popular" id="liveimage" src="http://example.com/webcams/suddenlypopular.jpg" />
<script type="text/javascript">
(function() {
    setInterval(function() {
        var myImageElement = document.getElementById('liveimage');
        var d = new Date();
        // 6000 is 6 seconds; the desired refresh rate
        // % n is a bit of an experiment for being nice on cache invalidation; it also puts a bound on how out-of-date something would be regarding clock skew.
        var timeSlice = Math.floor(d.getTime() / 6000) % 3;
        myImageElement.src = 'http://example.com/webcams/suddenlypopular.jpg?t=' + timeSlice;
    }, 6000);
}());
</script>

所以现在我有一个缓存友好的网络摄像头,它会更新。

Apache反向代理配置

这是一个来自Apache httpd的代码片段,说明如何反向代理网络摄像头来设置特定的缓存策略。

<Location /webcams/suddenlypopular.jpg>
  ProxyPass        http://mywebcamdevice.example.com/snapshot.jpg
  ProxyPassReverse http://mywebcamdevice.example.com/snapshot.jpg
  ExpiresByType image/jpeg "access plus 6 seconds"
  Header unset ETag
  Header unset Last-Modified
</Location>
相关文章: