我正在使用 MemoryStram 将 Bitmap 转换为 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 之前,只需倒回 Bitmap 编码到的那个,并设置 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;
}
请注意,还有其他方法可以在 Bitmap 和 BitmapImage 之间进行转换,例如这个:fast converting Bitmap to BitmapSource wpf
关于c# - WPF: MemoryStream 占用大量内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51444766/