Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you add image file to a image list in code?

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?

like image 551
muckdog12 Avatar asked Jul 22 '10 19:07

muckdog12


2 Answers

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
        }
like image 84
Paul Avatar answered Oct 16 '22 18:10

Paul


Like this

imageList.Images.Add(someImage);

Where someImage is an Image variable.

EDIT: Like this:

For Each path As String In Directory.GetFiles("Images\LanguageIcons")
    imageList.Images.Add(Image.FromFile(path))
Next
like image 22
SLaks Avatar answered Oct 16 '22 17:10

SLaks