c# - WPF: MemoryStream 占用大量内存

标签 c# wpf xaml

我正在使用 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/

相关文章:

c# - 如何访问自动实现的属性的支持变量?

c# - 从控件中绘制图像

c# - 将 .csv 文件读入 WPF 应用程序 (C#)

c# - 从页面绑定(bind)到窗口

C#/XAML Tapped 事件

c# - 如何在ViewModel中处理列表框keydown事件?

c# - 如何使用 Visual Studio Code 在 dotnet 构建中包含资源文件

WPF在鼠标下获取元素

Wpf DataGridComboBoxColumn 绑定(bind)在选择数据网格中的另一行后发生

silverlight - 如何在应用栏中集成枢轴控制?