【发布时间】:2017-01-13 03:27:44
【问题描述】:
我正在使用此函数将您的字节数组转换为图像,但是当此函数调用系统的内存使用量增加时。此函数可以调用大约 500 次。我尝试处理或刷新以使内存为空,但使用量仍在增加增加。我附上一个显示内存使用情况的任务管理器图像。
public static BitmapImage ConvertToBitmapImage(byte[] imageData)
{
if (imageData == null || imageData.Length == 0) return null;
var image = new BitmapImage();
using (var mem = new MemoryStream(imageData))
{
mem.Position = 0;
image.BeginInit();
image.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = null;
image.StreamSource = mem;
image.EndInit();
mem.Flush();
mem.Dispose();
}
image.Freeze();
return image;
}
【问题讨论】:
-
图片丢失。尽管如此。任务管理器不可靠。它显示系统保留的内存量。如果您的应用程序分配了几个大块,Windows 可能会决定为其预分配更多内存。
-
对不起,我已经编辑了你现在可以看到图像的帖子。应用程序没有分配大块,在这个函数调用获取图像之前大约需要 19mb。
-
此外,当您分配
new BitmapImage时,内存使用量也必须增加(因为我看不到您的其余代码,所以我不知道它保留了多长时间,所以我假设您不会立即丢弃它)-我们也没有关于您传入的图像有多大的信息 -
图像是 100x100 缩略图,在我的应用程序中,我从 web 服务获取字节数组形式的图像,然后使用此函数转换所有图像,每次此函数调用我的类模型的每个实例例如模型有字节数组和位图图像。我在我的应用程序中获得了大约 500 个实例。
-
void getImages(List<Model> models) { foreach(model in models) { model.Image=ConvertToBitmapImage (model.ByteArray); } }