我有一个WPF应用程序,我通过使用TiffBitmapEncoder将它们转换为TIFF图像来保存数百个BitmapSource中的几个。但是,我有这种奇怪的内存消耗,这往往是抛出内存不足的例外。TiffBitmapEncoder,在C#/ WPF中导致内存不足异常的内存错误
注:
- 我已经安装的RAM 8GB。
static void SaveBitmapSource(BitmapSource bitmapSource) { TiffBitmapEncoder encoder = new TiffBitmapEncoder(); encoder.Compression = TiffCompressOption.Zip; BitmapFrame frame = BitmapFrame.Create(bitmapSource); encoder.Frames.Add(frame); using (MemoryStream ms = new MemoryStream()) { encoder.Save(ms); } }
这里是我的记忆的屏幕截图:
- 图像尺寸从10×10到300×300像素(相当小)
这里是工作的代码变化
现在,如果我克隆BitmapSource(即使只是一次),然后我得到这个巨大的内存分配导致内存不足E xception。
static BitmapSource source2 = null;
static void SaveBitmapSource(BitmapSource bitmapSource)
{
if (source2 == null)
{
source2 = bitmapSource.Clone();
}
TiffBitmapEncoder encoder = new TiffBitmapEncoder();
encoder.Compression = TiffCompressOption.Zip;
BitmapFrame frame = BitmapFrame.Create(source2);
encoder.Frames.Add(frame);
using (MemoryStream ms = new MemoryStream())
{
encoder.Save(ms);
}
}
这是我记忆中的第二个代码示例
有谁知道这可能是造成这个问题以及如何解决它的截图?
不同之处在于第一个示例中的BitmapSource已呈现到屏幕上,第二个示例中没有。我怀疑是这可能是与GPU以及可能是硬件加速,其中有某种错误的而第二个是在CPU上进行转换的调度......
尝试:
- 试过
SaveBitmapSource()
没有运气
有没有什么处理source2? – BlueMonkMN
BitmapSource不实现IDisposable –
如果在函数末尾添加'GC.Collect()'会影响内存使用,那么好奇。不是一个解决方案,而是一个诊断步骤。 – BlueMonkMN