【问题标题】:Fetching Web Image and showing in Image control after interval - not working间隔后获取 Web 图像并在图像控件中显示 - 不起作用
【发布时间】:2017-07-03 10:02:47
【问题描述】:

我有一个自定义 UserControl,其中包含一个 Image 控件。我正在尝试从 web [网络服务器] 获取图像并将其显示在我的控件中,并使用调度程序计时器刷新源。代码如下:

  void StartSourceRefresh()
    {
        if (timeinterval < 1) timeinterval = 1;
        tmrRefresh.Tick += new EventHandler(dispatcherTimer_Tick);
        tmrRefresh.Interval = new TimeSpan(0, 0, timeinterval); //in hour-minute-second
        tmrRefresh.Start();
    }

    public void ChangeImageSource(string newSource)
    {
        //newSource = "http://192.168.1.3/abc/imagetobeshown.png"

        WebImg.Source = null;

        if (newSource.Trim() == "")
            WebImg.Source = new BitmapImage(new Uri(@imagePlaceholder, UriKind.Absolute));
        else
        {
            BitmapImage image = new BitmapImage();
            image.BeginInit();
            image.UriSource = new Uri(@newSource, UriKind.Absolute);
            image.EndInit();
            WebImg.Source = image;
        }
    }

    private void dispatcherTimer_Tick(object sender, EventArgs e)
    {
      ChangeImageSource(txtImgSrc.Text.Trim());
    }

问题是图像不会改变。它显示与第一次获取的相同。定时器运行良好。但图像不会改变。我在这里做错了什么?

编辑:网络源在一定间隔后刷新,因此必须获取相同的源

【问题讨论】:

标签: c# .net wpf image


【解决方案1】:

您显然是从默认缓存的相同图像 URL 重新加载。

通过设置BitmapCreateOptions.IgnoreImageCache禁用缓存:

var image = new BitmapImage();
image.BeginInit();
image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
image.UriSource = new Uri(newSource);
image.EndInit();

【讨论】:

  • 图片的网络源会在一定的时间间隔后刷新,从而改变图片。所以我必须获取相同的来源
  • 这就是为什么你应该绕过缓存。
  • 显然 `new BitmapImage(new Uri(newSource), new RequestCachePolicy(RequestCacheLevel.BypassCache));` 对我不起作用。但另一个工作得很好。
  • 使用 BitmapCreateOptions.IgnoreImageCache 后,图像会闪烁一微秒左右。我猜当缓存被清除时,如果我没记错的话,那段时间的图像源会变为空。但是有什么办法可以消除这种闪烁?
  • 闪烁是由于后台线程异步加载BitmapImage所致。当您分配WebImg.Source = image 时,图像尚未加载,因此图像控件显示一个空图像。请参阅this answer,了解如何在分配给 Source 属性之前异步加载图像。另一种方法可能是将 DownloadCompleted 处理程序附加到 BitmapImage 并在该处理程序中分配 Source 属性。
猜你喜欢
  • 2012-07-05
  • 2014-03-19
  • 2018-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-03
  • 1970-01-01
相关资源
最近更新 更多