显示图像控件中目录的每个图像

时间:2011-09-14 18:05:43

标签: c# wpf image wpf-controls

我想在Image控件中显示本地目录中的内容(.jpg文件)。图像必须以5秒的延迟替换。

    DirectoryInfo dir = new DirectoryInfo(@"D:\somedir");
            FileInfo[] files = dir.GetFiles();

            foreach (var item in files)
            {
                imgBox.Source = (ImageSource)new ImageSourceConverter().ConvertFromString(item.FullName);
            }

1 个答案:

答案 0 :(得分:2)

将图像加载到内存中,然后使用后台线程以定义的延迟旋转它们。需要调度程序调用才能从后台线程访问UI控件。

List<Image> images;

void GetImagesIntoAList()
{
    List<Image> images = new List<Image>();

    DirectoryInfo dir = new DirectoryInfo(@"D:\somedir");
                FileInfo[] files = dir.GetFiles();

                foreach (var item in files)
                {                        
                   FileStream stream = new FileStream(item.FullName, FileMode.Open, FileAccess.Read);
                   Image i = new Image();
                   BitmapImage src = new BitmapImage();
                   src.BeginInit();
                   src.StreamSource = stream;
                   src.EndInit();
                   i.Source = src;
                   images.Add(i);
                }

   Thread rotator = new Thread(rotate);
   rotator.Start();
}

void rotate()
{
   foreach(var img in images)
   {
      Dispatcher.BeginInvoke( () => 
      { 
         nameOfImageControlOnAWindow.Source = img;

      }
      );

      Thread.Sleep(5000);
   }
}