【问题标题】:WPF: MemoryStream Occupying large amount of memoryWPF:MemoryStream 占用大量内存
【发布时间】: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 的调用?

标签: c# wpf xaml


【解决方案1】:

不需要第二个 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

【讨论】:

  • 感谢您的帮助,给定的链接 fast convert Bitmap to BitmapSource wpf 提供了更好的性能。
猜你喜欢
  • 2014-05-11
  • 2011-02-27
  • 2013-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多