javascript 使用ajax刷新网络摄像头图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5883195/
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-10-25 18:40:24  来源:igfitidea点击:

webcam image refresh with ajax

javascripthtmlajax

提问by zillaofthegods

I have an image that is being constantly updated from a local webcam source, it is then displayed on a website. I can get the image to show and by refreshing the page the image will update (obviously).

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

What I am wondering is, how can I update this image every (lets say) 5 seconds, without having to refresh the page manually (ie. utilizing ajax).

我想知道的是,我怎样才能每(比如说)5 秒更新一次这个图像,而不必手动刷新页面(即使用 ajax)。

Basic things I am not too sure about:

我不太确定的基本事情:

  1. <img src=""/><--- how can I load an image url that is located within the javascript code

  2. within the javascript code, how can I create a function that will automatically update the image source, without having to reload the page

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

  2. 在javascript代码中,如何创建一个无需重新加载页面即可自动更新图像源的函数

As I understand it, upon reading around, one of the main problems is that browsers will load the cached image unless the resulting httprequest looks different each time, as such am I required to add an additional item within the url string (ie. www.yoursire.com?image=foo&date=bar (the date is grabbed by date function or some other iterated value)) in order to circumvent this horrible browser predisposition?

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

Thanks in advance!

提前致谢!

回答by Richard H

Without writing allthe code

无需编写所有代码

  • look at the javascript functions setTimeout()and setInterval()

  • it's easy to change the src attribute of ana element

    document.getElementbyId("imageId").setAttribute("src", imageUrl);
    
  • if your image request url is the same everytime (but the pic has changed server-side) you can either add a "no-cache" to the ajax request header, or possibly add a random query string to the image to force a reload each time (e.g http://mydomain/myimage?3754854)

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

  • 很容易改变 ana 元素的 src 属性

    document.getElementbyId("imageId").setAttribute("src", imageUrl);
    
  • 如果您的图像请求 url 每次都相同(但图片已更改服务器端),您可以向 ajax 请求标头添加“无缓存”,或者可能向图像添加随机查询字符串以强制重新加载每个时间(例如http://mydomain/myimage?3754854

回答by Nathan

With jQuery:

使用 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);


}

(the force refresh thing is to prevent browser from using locally cached image)

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

回答by Aliostad

I have done this and it works using setting the image source. Also on the server-side, you have to send no-cache HTTP headersto prevent caching.

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

<img src="" id="webcam" />
<script type="text/javascript">

var int=self.setInterval("reload()",1000);

function reload(){
   $("#webcam").attr("src", "/mysite/webcamImage");
}

</script>

回答by rzetterberg

You could use jquery to load an image object and then attach a timer and run the code for every 5 seconds.

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

Here's an example:

下面是一个例子:

// 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');
});

Read more about this here:

在此处阅读更多相关信息:

About preventing the caching of dynamically loaded images you can just add the last modified timestamp in the url:

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

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

回答by Shaun3180

I had the same need, so I'm appending my own js solution below. Occasionally our webcam will be in the middle of writing the jpg to a directory when the ajax refresh occurs, so instead of displaying a broken image, I'm presenting an animated gif.

我有同样的需求,所以我在下面附加了我自己的 js 解决方案。有时,我们的网络摄像头会在发生 ajax 刷新时将 jpg 写入目录,因此我不会显示损坏的图像,而是显示动画 gif。

JS:

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();
    })();
});

HTML

HTML

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

回答by Cameron Kerr

Disabling caching will overwhelm your webcam (even good ones) if it gets popular

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

I tried allowing the image to be allowed to be cached for 6 seconds (Cache-Control: max-age=6), because I needed to prevent a webcam from being overwhelmed. The code that I was working with looked a bit like this, but it has a problem:

我尝试允许图像缓存 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>

Previously, the web-developer had put a ?rand=(random-number) in as a cache-busting technique. That's bad when the image is cacheble (even if only for a short period of time), because if means that you may (depending on whether your cache will consider query parameters as non-cachable), mean you get a very poor cache hit rate and you get a lot of page representations being built up.

以前,Web 开发人员已将 ?rand=(random-number) 作为缓存破坏技术。当图像可缓存时(即使只有很短的时间)这很糟糕,因为如果意味着您可能(取决于您的缓存是否将查询参数视为不可缓存的),则意味着您的缓存命中率非常低并且您会构建大量页面表示。

The problem was that the image was now not refreshing, because although the src attribute was being reassigned, it wasn't actually changing to a different value, so the browser (Chrome 51) wasn't updating the image. I changed the logic to have either an ?1or a ?2query string argument, and alternate between them.

问题是图像现在没有刷新,因为虽然 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: While this works in Chrome and IE, it didn't work in Firefox, so I came up with an alternative solution that is working in Chrome, Firefox and IE (Safari is currently untested).

编辑:虽然这在 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>

So now I have a cache-friendly webcam that does update.

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

Apache reverse-proxy configuration

Apache 反向代理配置

Here's a snippet from Apache httpd for how you might reverse-proxy a webcam to set a particular caching policy.

这是 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>