user3384676
user3384676

Reputation: 79

How can I make a for loop to load images to my application using C#?

I have an application that I need to load some images from my folder to the application as a bmp bitmap image and for that purpose I am using the following code:

Then I need to iterate throw each images line by line and make a separate list for each image (list1, list2, etc.) which contains only zero and ones (the images are only black and white)

My problem is for finite number of images I can copy the same code (for example for 5 images) five time, but for large number of images (for example 100 images) is not possible, I just wanted to know how to turn this code in a for loop that looks for a number of images (for example 100) and I get different lists (list1, list2, list3, etc.) as output.

Upvotes: 0

Views: 718

Answers (2)

Mahdi Tahsildari
Mahdi Tahsildari

Reputation: 13582

Assuming all files in the path are Images you can do the following:

var images = new List<Bitmap>();
var files = Directory.GetFiles(path);
for (int i = 0; i < files.Count(); i++)
{
    string nextimage = files[i];
    Bitmap bmp1 = Bitmap.FromFile(nextimage) as Bitmap
    images.Add(bmp1); //to keep images in RAM for later process
    bmp1.Save(somePath + "\\bmp" + i.ToString()); // to save images on disc
}

And it's not a good idea to load (n) images one after each other, because you will only see the last one. So you'd better show one of them, for example:

pictureBox1.Image = Bitmap.FromFile(files[files.Count() - 1]) as Bitmap;

Upvotes: 2

David
David

Reputation: 218798

You'd need a collection of Bitmap objects, then just iterate through the files in the directory to load them all. Perhaps something like this:

var images = new List<Bitmap>();
foreach (var file in Directory.GetFiles(@"C:\myfolder\"))
    images.Add(Bitmap.FromFile(file) as Bitmap);

You can optionally add a filter and other options to Directory.GetFiles() to narrow down the search, if the directory contains other files which you don't want to load as bitmaps.

Upvotes: 1

Related Questions