【发布时间】:2018-07-20 14:27:54
【问题描述】:
我正在使用 MemorySram 将 Bitmap 转换为 BitmapImage,当我检查 CPU 使用率时,它消耗了更多内存。我想减少 MemoryStream 对象的内存消耗。我也在 Using 语句中使用它,结果与前面提到的相同。 我正在拍我的代码 sn-p 请任何人都可以帮助我找到解决方案或可以使用的任何其他替代方案。 代码:
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;
}
【问题讨论】:
-
看起来您可以省略内存流,也可以通过将
Bitmap.Save的结果直接输入bImg.StreamSource来省略对ToArray的调用?