简体   繁体   English

WPF:MemoryStream占用大量内存

[英]WPF: MemoryStream Occupying large amount of memory

I am using MemoryStram for converting Bitmap to BitmapImage and when I checked the CPU usage it is consuming more memory. 我正在使用MemoryStram将Bitmap转换为BitmapImage,当我检查CPU使用率时,它消耗的内存更多。 I wanted to reduce the memory consumption of MemoryStream object. 我想减少MemoryStream对象的内存消耗。 I used it in Using statement also and the result is same as earlier mentioned. 我也在Using语句中使用它,结果与前面提到的相同。 I am pating my code snippet please can anyone help me out to find the solution or any other alternative that can be used. 我正在考虑我的代码片段,请任何人帮助我找到解决方案或任何其他可以使用的替代方案。 Code : 代码:

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;
    }
}

Or 要么

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;
}

There is no need for a second MemoryStream. 不需要第二个MemoryStream。

Just rewind the one that the Bitmap was encoded to, before decoding the BitmapImage, and set BitmapCacheOption.OnLoad to make sure that the stream can be closed after EndInit() : 在解码BitmapImage之前, EndInit() 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;
}

Note that there are also other ways of converting between Bitmap and BitmapImage, eg this: fast converting Bitmap to BitmapSource wpf 请注意,还有其他方法可以在Bitmap和BitmapImage之间进行转换,例如: 快速转换Bitmap到BitmapSource wpf

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM