c# - 图像的 WPF 内存问题

标签 c# wpf

我似乎遇到了一些内存消耗大的问题。当我第一次加载包含 gridview 和 observablecollection 的 wpf 应用程序时,该应用程序大约有 10mb。

当我单击 gridview 中的一个项目时,它会打开另一个窗口,其中包含一个图像控件,该控件传递一个 base64 字符串,然后我将其转换为 BitmapImage

然后应用程序从 10mb 跳到大约 123mb。原始图像大小为 64k,但我所有存储的图像都是 base64 字符串,我将其转换回 byte[],然后转换为 BitmapImage。 是的,我的意思是这样做。

当我关闭窗口时,没有任何 ram 被释放。我什至尝试过调用 GC。

我用下面的代码把base64图片转成

var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.CacheOption = BitmapCacheOption.None;
bitmapImage.StreamSource = new SIO.MemoryStream(imageBytes);
bitmapImage.EndInit();
return bitmapImage;

然后将其分配给 Image.Source

最佳答案

下面是一些提示和猜测,但是如果您使用内存分析器,您将能够看到什么占用了内存。 (例如 the CLR profiler also VS 2012 ad 2013 come in-built memory profile tools 和其他商业应用: .NET Memory Profiling Tools )


  • 为什么从 here 指定 CacheOption BitmapCacheOption.None上面写着:

Do not create a memory store. All requests for the image are filled directly by the image file.

相反,您可以使用 OnLoad:

Caches the entire image into memory at load time. All requests for image data are filled from the memory store.

我读作:如果您在许多位置显示图像,它们共享相同的底层内存。因此,如果您在不止一个地方展示同一张图片,那当然更好。

  • 在示例评论中找到的另一个提示 here :

To save significant application memory, set the DecodePixelWidth or
DecodePixelHeight of the BitmapImage value of the image source to the desired height and width of the rendered image. If you don't do this, the application will cache the image as though it were rendered as its normal size rather then just the size that is displayed.

  • 为什么要使用 base64 字符串,为什么不使用二进制数据,即 byte[]?您对每个字符串有多少个副本?

关于c# - 图像的 WPF 内存问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20650055/

相关文章:

c# - 点击背景时 Viewport3D 鼠标事件不会触发

WPF ContentPresenter 覆盖同一级别的其他控件

c# - 用户单击 MessageDialog 上的按钮时如何调用 FileSavePicker?

c# - 整行 telerik 的绑定(bind)背景(颜色):GridViewDataControl WPF control

c# - 搜索大量大文本列表的最快方法

c# - 为 Bing 搜索 API 的 DataServiceQuery 添加分页功能

wpf - 如何在 WPF ScrollViewer 中增加滚动条宽度?

.net - 从 ViewModel 中的 Observable 集合中移除不会更新 View,但 Updates of Existing Items 会更新 View

c# - 如何向此 ASP.NET DropDownList 控件添加默认的 "Select"选项?

c# - WPF 复合窗口和 ViewModel