How to display a downloaded image in WPF window
I need to download a webcam image thru http, and refresh it at 10fps and display it on a WPF window. Right now I'm using this code:
Window1 wndMain;
BitmapImage img;
DispatcherTimer tmrRefresh;
public WCam(Window1 wndMain, string imguri)
{
this.wndMain = wndMain;
this.MouseLeftButtonDown += delegate { DragMove(); };
url = imguri;
InitializeComponent();
tmrRefresh = new DispatcherTimer(TimeSpan.FromMilliseconds(100),
DispatcherPriority.Normal, Refresh, Dispatcher.CurrentDispatcher);
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
if (url != "")
{
try
{
img = new BitmapImage();
img.BeginInit();
img.CacheOption = BitmapCacheOption.OnLoad;
img.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
img.UriSource=(new Uri(url));
img.EndInit();
}
catch (Exception ex)
{
new WPopup().Show(ex.Message);
}
ImgBox.Source = img;
tmrRefresh.Start();
}
}
public void Refresh(object sender, EventArgs e)
{
开发者_如何学编程 try
{
img = new BitmapImage();
img.BeginInit();
img.CacheOption = BitmapCacheOption.OnLoad;
img.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
img.UriSource = (new Uri(url));
img.EndInit();
}
catch (Exception ex)
{
new WPopup().Show(ex.Message);
}
ImgBox.Source = null;
ImgBox.Source = img;
}
It displays nothing, if I increase the timer interval to 1000 it displays images but the image goes away while it loads the next one. Also the window loads in awfully slowly.
Seperate the loading logic from the image. Keep the loaded code as is, the refresh should download the image with a simple async(to keep ui running) request and only when finished change the image source to the local memory.
精彩评论