加载.JPG时出现系统内存不足异常
本文关键字:系统 内存不足 异常 JPG 加载 | 更新日期: 2023-09-27 18:31:47
我正在尝试将用户图片文件夹中的整个图像集合放入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
谁能告诉我为什么会这样?谢谢
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);
}
要添加到 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);
}
}