Niranjan
Niranjan

Reputation: 823

Displaying each image from a directory in an Image Control

I'd like to display the contents(.jpg files) from a local directory in an Image control. The images has to be replaced with a 5 sec delay.

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

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

Upvotes: 1

Views: 2143

Answers (1)

Maxim V. Pavlov
Maxim V. Pavlov

Reputation: 10509

Load images into a memory, then user a background thread to rotate them with the defined delay. Dispatcher call is required to access the UI control from a background thread.

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

Upvotes: 2

Related Questions