WPF:MemoryStream占用大量内存



我使用MemoryTram将位图转换为BitmapImage,当我检查CPU使用情况时,它消耗了更多的内存。我想减少MemoryStream对象的内存消耗。我在Using语句中也使用了它,结果和前面提到的一样。我正在整理我的代码片段,请任何人帮助我找到解决方案或任何其他可以使用的替代方案。代码:

public static BitmapImage ConvertBitmapImage(this Bitmap bitmap)
{
using (MemoryStream ms = new MemoryStream())
{
bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
System.Windows.Media.Imaging.BitmapImage bImg = new System.Windows.Media.Imaging.BitmapImage();
bImg.BeginInit();
bImg.StreamSource = new MemoryStream(ms.ToArray());
bImg.EndInit();
return bImg;
}
}

public static BitmapImage ConvertBitmapImage(this Bitmap bitmap)
{
BitmapImage bi = new BitmapImage();
bi.BeginInit();
MemoryStream ms = new MemoryStream();
bitmap.Save(ms, ImageFormat.Bmp);
ms.Seek(0, SeekOrigin.Begin);
bi.StreamSource = ms;
bi.EndInit();
return bi;
}

不需要第二个MemoryStream。

在解码BitmapImage之前,只需倒带位图编码到的位图,并设置BitmapCacheOption.OnLoad以确保在EndInit():之后可以关闭流

public static BitmapImage ConvertBitmapImage(this System.Drawing.Bitmap bitmap)
{
var bImg = new BitmapImage();
using (var ms = new MemoryStream())
{
bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
ms.Position = 0; // here, alternatively use ms.Seek(0, SeekOrigin.Begin);
bImg.BeginInit();
bImg.CacheOption = BitmapCacheOption.OnLoad; // and here
bImg.StreamSource = ms;
bImg.EndInit();
}
return bImg;
}

注意,位图和BitmapImage之间还有其他转换方式,例如:将位图快速转换为BitmapSource wpf

最新更新