-3

I'm looking for how to create a collection of images from a directory and then instantiate all the images dynamically.

Actually I instantiate my images as follows:

    private BitmapSource orange = BitmapUtil.FromImages("orange.png");
    private BitmapSource lemon = BitmapUtil.FromImages("lemon.png");
    private BitmapSource apple = BitmapUtil.FromImages("apple.png");

But the problem is that, let's say someone add new fruits in the directory that contains all these images of fruits. I want to instantiate all of these fruits dynamically so when we run the program, it checks for all the images in the folder /fruits/... and then create this list of elements.

Edit: I want to do this using BitmapSource and BitmalUtil.FromImages because I still want to manipulate those images within a method. I don't want to store them randomly in a list.

LiquidSnake
  • 375
  • 1
  • 4
  • 16

1 Answers1

3

Something like this:

List<BitmapSource> images = new List();
foreach (var filePath in Directory.GetFiles("Fruit"))
{
    images.Add(BitmapUtil.FromImages(filePath));
}

You may as well use LINQ:

var images = Directory.EnumerateFiles("Fruit")
    .Select(f => BitmapUtil.FromImage(f))
    .ToList();
Clemens
  • 123,504
  • 12
  • 155
  • 268
Robin Bennett
  • 3,192
  • 1
  • 8
  • 18