Flanker
Flanker

Reputation: 89

Out of memory exception when adding images to image list and displaying them into a list view

I am in the process to making an image gallery where i need to load more than 2 GB images from 1 directory to list view.

when i browse a folder above 200 mb its showing me the error OUT OF MEMORY.

my code is

        _filenames = new List<string>();
             DirectoryInfo dir = new DirectoryInfo(@root + "gallery");
            foreach (FileInfo file in dir.GetFiles())
            {
               if (file.Name != "desktop.ini")
                {
                    var image = Image.FromFile(file.FullName);
                    _filenames.Add(file.Name.ToLower());
                    imageList1.Images.Add(image);
                }
                else
                {
                    break;
                }

            }                           
            listView1.View = View.LargeIcon;
            imageList1.ImageSize = new Size(75,75);
            listView1.LargeImageList = imageList1;
            for (int i = 0; i < imageList1.Images.Count; i++)
            {
                var item = new ListViewItem();
                item.ImageIndex = i;
                item.Text = _filenames[i];
                listView1.Items.Add(item);
            }

        }

Upvotes: 1

Views: 1597

Answers (1)

ne1410s
ne1410s

Reputation: 7082

You need to (as a first), perform your image operations before adding them to the list:

Performing other operations, such as setting the ColorDepth or ImageSize will cause the Handle to be recreated. Therefore, you should perform these operations before you add images to the ImageList.

from MSDN

Update following clarifications:

In order to create your own file list then (assuming you have the directory name and file names within the directory) you could create a FileInfo[] array as follows:

// Prepare the directory and file names
var directoryName = "C:\\Temp\\MyFolder";
var filenames = new List<string>();
filenames.Add("0001.jpg");
filenames.Add("2345.jpg");

// Construct FileInfo array - using System.IO
var files = new FileInfo[filenames.Count];
for (var i = 0; i < filenames.Count; i++)
{
    var fileName = filenames[i];
    files[i] = new FileInfo(Path.Combine(directoryName, fileName));
}

There are many ways you could construct the FileInfo[] array (e.g. LINQ for example), but the above should work fine.

Upvotes: 2

Related Questions