C# 如何在wpf应用程序中配置BitmapDecoder对象

C# 如何在wpf应用程序中配置BitmapDecoder对象,c#,wpf,C#,Wpf,我开发了一个WPF应用程序,使用BitmapDecoder保存图像。在保存图像时,我得到了一个 内存不足,无法完成操作异常 代码如下所示: BitmapDecoder imgDecoder = BitmapDecoder.Create(mem, BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.None); 我认为BitmapDecoder对象可能是该异常的原因;如何处置对象?位图解码器不是一次性的。如果不再需要BitmapDe

我开发了一个WPF应用程序,使用
BitmapDecoder
保存图像。在保存图像时,我得到了一个

内存不足,无法完成操作异常

代码如下所示:

BitmapDecoder imgDecoder = BitmapDecoder.Create(mem,
BitmapCreateOptions.IgnoreColorProfile, BitmapCacheOption.None);

我认为BitmapDecoder对象可能是该异常的原因;如何处置对象?

位图解码器不是一次性的。如果不再需要BitmapDecoder,请确保不保留任何对它的引用,GC将完成其工作并在需要时收集未使用的内存。

我遇到了同样的问题。我有一个应用程序,它使用BitmapDecoder加载了数千张图像,并且遇到了内存问题。我必须创建一个包装类ImageFileHandler来处理与BitmapDecoder的所有交互,然后将我的BitmapDecoder实例存储在WeakReference中。因此,如果操作系统需要内存,我的弱引用将放弃BitmapDecoder,然后每次我的ImageFileHandler需要它时,它都会在必要时创建一个新的。不仅BmpBitmapDecoder,而且所有解码器(GifBitmapDecoder、PngBitmapDecoder、JpegBitmapDecoder、TiffBitmapDecoder)都不是一次性类,所以你能做的就是说

_myDecoder = null; 
GC.Collect();

让垃圾收集器完成它的工作

如果愿意,您可以创建一个
BitmapDecoder
s池,并将图像作为
FileStream
加载,这些图像是一次性的,包含图像的二进制数据。也许下面的代码给了你一个想法:

GC.Collect();
// Load the file stream if it hasn't been loaded yet
if (_imageDataStream == null)
    _imageDataStream = new FileStream(_imagePath, FileMode.Open, FileAccess.Read, FileShare.Read);
else
    _imageDataStream.Seek(0, SeekOrigin.Begin);

string extension = System.IO.Path.GetExtension(_imagePath).ToUpper();
if (extension.Contains("GIF"))
    _decoder = new GifBitmapDecoder(_imageDataStream, BitmapCreateOptions.PreservePixelFormat,
        BitmapCacheOption.OnDemand);
else if (extension.Contains("PNG"))
    _decoder = new PngBitmapDecoder(_imageDataStream, BitmapCreateOptions.PreservePixelFormat,
        BitmapCacheOption.OnDemand);
else if (extension.Contains("JPG") || extension.Contains("JPEG"))
    _decoder = new JpegBitmapDecoder(_imageDataStream, BitmapCreateOptions.PreservePixelFormat,
        BitmapCacheOption.OnDemand);
else if (extension.Contains("BMP"))
    _decoder = new BmpBitmapDecoder(_imageDataStream, BitmapCreateOptions.PreservePixelFormat,
        BitmapCacheOption.OnDemand);
else if (extension.Contains("TIF"))
    _decoder = new TiffBitmapDecoder(_imageDataStream, BitmapCreateOptions.PreservePixelFormat,
        BitmapCacheOption.OnDemand);

仅供参考,您应该“接受”和/或投票表决您的问题的正确答案。这就是人们在StackOverflow上说“谢谢”的方式。我想我也遇到了同样的问题。请您再描述一下您的解决方案好吗?“让垃圾收集器完成它的工作”——所以不要强迫GC进行收集。在大多数情况下,GC知道该做什么。调用“GC.Collect()”和其他GC函数可能会导致性能问题。