Out of memory exception while loading images

前端 未结 4 1588
予麋鹿
予麋鹿 2021-01-14 06:23

I am using the following piece of code to load images as thumbnails to a FlowLayoutPanel control. Unfortunately i get an OutOfMemory exception.

As you already guess

4条回答
  •  深忆病人
    2021-01-14 06:59

    I had the same problem. Jim Mischel answer led me to discover loading an innocent .txt file was the culprit. Here's my method in case anyone is interested.

    Here's my method:

    /// 
    /// Loads every image from the folder specified as param.
    /// 
    /// Path to the directory from which you want to load images.  
    /// NOTE: this method will throws exceptions if the argument causes 
    /// Directory.GetFiles(path) to throw an exception.
    /// An ImageList, if no files are found, it'll be empty (not null).
    public static ImageList InitImageListFromDirectory(string pDirectory)
    {
        ImageList imageList = new ImageList();
    
        foreach (string f in System.IO.Directory.GetFiles(pDirectory))
        {
            try
            {
                Image img = Image.FromFile(f);
                imageList.Images.Add(img);
            }
            catch
            {
                // Out of Memory Exceptions are thrown in Image.FromFile if you pass in a non-image file.
            }
        }
    
        return imageList;
    }
    

提交回复
热议问题