加载.JPG时出现SystemOutOfMemory异常

时间:2014-11-24 13:46:21

标签: c#

我试图将用户的图片文件夹中的整个图像集合放入ObservableCollection(图像)。如果我只获得.png,那么它可以正常工作,但如果我也尝试获取.jpg,则会抛出SystemOutOfMemory异常。我使用以下代码:

String picturesPath = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
String[] files = Directory.GetFiles(picturesPath, "*", SearchOption.AllDirectories);

foreach (String file in files)
{
    ImageInfo newImage = new ImageInfo() { Id = Guid.NewGuid().ToString(), Path = file };    //Id and Path are properties of newImage, defined by the ImageInfo class
    if (file.EndsWith(".png") || file.EndsWith(".jpg")) Images.Add(newImage);
}

编辑:我使用以下代码将图像添加到StackPanel。 (RibbonButton是自定义组件)。

foreach (ImageInfo image in startup.Images)
        {
            Image newImage = new Image();
            newImage.Source = new BitmapImage(new Uri(image.Path, UriKind.RelativeOrAbsolute));
            RibbonButton newRibbonButton = new RibbonButton();
            RibbonButton.SetCornerRadius(newRibbonButton, new CornerRadius(0));
            SolidColorBrush brush = new SolidColorBrush(Colors.DarkGray);
            RibbonButton.SetIsPressedBackground(newRibbonButton, brush);
            newRibbonButton.Content = newImage;
            newRibbonButton.ToolTip = image.Path;
            newRibbonButton.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Center;
            newRibbonButton.Margin = new Thickness(5);
            newRibbonButton.Width = 100;
            newRibbonButton.Height = 60;
            imagesListStackPanel.Children.Add(newRibbonButton);
        }

编辑:OnPropertyChanged处理程序:

#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
#region OnPropertyChanged
protected void OnPropertyChanged(string propertyName)
{
    PropertyChangedEventHandler handler = this.PropertyChanged;
    if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
#endregion OnPropertyChanged

谁能告诉我为什么会这样?感谢

2 个答案:

答案 0 :(得分:4)

Directory.GetFiles将所有文件名加载到内存中。如果您不需要全部,可以使用EnumerateFiles

foreach(var file in Directory.EnumerateFiles(picturesPath, "*", SearchOption.AllDirectories))

或通过LINQ,您可以让它更清洁:

var images = Directory.EnumerateFiles(picturesPath, "*", SearchOption.AllDirectories)
        .Where(f => Path.GetExtension(f) == ".png" || Path.GetExtension(f) == ".jpg")
        .Select(file => new ImageInfo() 
                        { 
                           Id = Guid.NewGuid().ToString(),  
                           Path = file 
                        });

foreach(var img in images)
{
   Images.Add(img);
}

答案 1 :(得分:0)

要添加到Selmen22的解决方案,您可以重新构建逻辑,以避免加载图片并创建您不感兴趣的ImageInfo个实例。

foreach (var file in Directory.EnumerateFiles(picturesPath, "*", SearchOption.AllDirectories))
{
    if (file.EndsWith(".png") || file.EndsWith(".jpg"))
    {
        ImageInfo newImage = new ImageInfo() { Id = Guid.NewGuid().ToString(), Path = file };
        Images.Add(newImage);
    }
}