[英]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: 我有一个应用程序,我需要将一些图像从我的文件夹加载到应用程序作为bmp位图图像,为此我使用以下代码:
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) 然后我需要迭代逐行抛出每个图像并为每个图像(list1,list2等)创建一个单独的列表,其中只包含0和1(图像只有黑色和白色)
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. 我的问题是有限数量的图像我可以复制相同的代码(例如5个图像)五次,但是对于大量的图像(例如100个图像)是不可能的,我只是想知道如何转换这个代码在寻找多个图像(例如100)的for循环中,我得到不同的列表(list1,list2,list3等)作为输出。
Assuming all files in the path are Images you can do the following: 假设路径中的所有文件都是Images,您可以执行以下操作:
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. 并且一个接一个地加载(n)图像并不是一个好主意,因为你只会看到最后一个。 So you'd better show one of them, for example: 所以你最好展示其中一个,例如:
pictureBox1.Image = Bitmap.FromFile(files[files.Count() - 1]) as Bitmap;
You'd need a collection of Bitmap
objects, then just iterate through the files in the directory to load them all. 您需要一组Bitmap
对象,然后只需遍历目录中的文件即可加载它们。 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. 如果目录包含您不希望作为位图加载的其他文件,则可以选择向Directory.GetFiles()
添加过滤器和其他选项以缩小搜索范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.