I have an image list and would like to add a directory of images to the image list in my code. How would I do this? When I run the code:
'Load all of the items from the imagelist
For Each path As String In Directory.GetFiles("Images\LanguageIcons\")
imlLanguagesIcons.Images.Add(Image.FromFile(path))
Next
I get an out of memory exception. Currently there is only 14 images so there really shouldn't be a problem. Any Help?
image.Dispose() fixes the out of memory exception. The detailed approach which I used is (although overkill for some):
ImageList galleryList = new ImageList();
string[] GalleryArray = System.IO.Directory.GetFiles(txtSourceDir.Text); //create array of files in directory
galleryList.ImageSize = new Size(96, 64);
galleryList.ColorDepth = ColorDepth.Depth32Bit;
for (int i = 0; i < GalleryArray.Length; i++)
{
if (GalleryArray[i].Contains(".jpg")) //test if the file is an image
{
var tempImage = Image.FromFile(GalleryArray[i]); //Load the image from directory location
Bitmap pic = new Bitmap(96, 64);
using (Graphics g = Graphics.FromImage(pic))
{
g.DrawImage(tempImage, new Rectangle(0, 0, pic.Width, pic.Height)); //redraw smaller image
}
galleryList.Images.Add(pic); //add new image to imageList
tempImage.Dispose(); //after adding to the list, dispose image out of memory
}
}
lstGallery.View = View.LargeIcon;
lstGallery.LargeImageList = galleryList; //set imageList to listView
for (int i = 0; i < galleryList.Images.Count; i++)
{
ListViewItem item = new ListViewItem();
item.ImageIndex = i;
lstGallery.Items.Add(item); //add images in sequential order
}