繁体   English   中英

Memory“泄漏”与 MemoryStream 和 BitmapCacheOption.OnLoad

[英]Memory 'leak' with MemoryStream and BitmapCacheOption.OnLoad

我必须从图像中获取 BitmapSource,为此我使用如下扩展方法:

public static BitmapSource ToBitmapSource(this Image image)
{
    LogEx.FunctionEnter();

    if (image == null)
        throw new ArgumentNullException("image");

    BitmapImage bitmapImage = null;
    using (MemoryStream memory = new MemoryStream())
    {
        image.Save(memory, ImageFormat.Jpeg);
        memory.Position = 0;
        bitmapImage = new BitmapImage();
        bitmapImage.BeginInit();
        bitmapImage.StreamSource = memory;
        bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
        bitmapImage.EndInit();
    }

    LogEx.FunctionLeave("Rendered image as BitmapSource");
    return bitmapImage;
}

如果我现在释放它的句柄并处理原始图像,它会保留在 memory 中,即使在多次手动调用 GC 之后也是如此。 我用这段代码测试了使用文件而不是流:

string filename = $"c:\\temp\\{page}.jpg";
if (File.Exists(filename))
{
    File.Delete(filename);
}
_highResPageImages[page].Save(filename, ImageFormat.Jpeg);
Uri uri = new Uri(filename);
BitmapImage source = new BitmapImage();
source.BeginInit();
source.UriSource = uri;
source.CacheOption = BitmapCacheOption.OnLoad;
source.EndInit();
Document.PageImage = source;
// Ducument.PageImage = _highResPageImages[page].ToBitmapSource();

即使还有一个 OnLoad,它也会在释放句柄时被释放。 所以它一定是 MemoryStream 的东西。 但是什么? 我尝试了在其他地方找到的 WrapperStream,并使用了 BitmapImage 的 Freeze() 方法,但都无济于事。 问题是,我无法将图像缓存在客户的驱动器上(即使这样做不会花费大量时间)并且我从另一个 DLL 获取图像,所以我无法事先更改它。 别人有想法吗?

编辑:我使用 WPF 并且句柄的值正在用于显示的绑定中。 也许这在某种程度上很重要。 或者我在 Binding 和句柄中使用 BitmapSource 而不是原始 BitmapImage。

ToBitmapSource试试这个:

...
bitmapImage.StreamSource = null;
return bitmapImage

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM