user296623
user296623

Reputation: 345

WPF BitmapImage Memory Usage

I am trying to convert a byte array of an image to BitmapImage to bind to a button.

public static BitmapImage GetBitmapImageFromByteArray(byte[] p_Image)
    {
        try
        {
            BitmapImage bmpImage;
            if (p_Image != null)
            {
                using (MemoryStream msStream = new MemoryStream(p_Image))
                {
                    msStream.Position = 0;
                    bmpImage = GetBitmapImageFromStream(msStream);
                    //msStream.Close();
                    return bmpImage;
                }
            }
        }
        catch
        {
        }
        return null;
    }

Where GetBitmapImageFromStream looks something like this:

public static BitmapImage GetBitmapImageFromStream(MemoryStream msImage)
    {
        try
        {
            if (msImage == null) return null;
                BitmapImage bmpImg = new BitmapImage();
                msImage.Position = 0;
                bmpImg.BeginInit();
                bmpImg.CacheOption = BitmapCacheOption.OnLoad;
                bmpImg.StreamSource = msImage;
                bmpImg.EndInit();
                return bmpImg;

        }
        catch
        {
            return null;
        }
    }

On bmpImg.EndInit(), there is this huge spike in memory. And I have many buttons on my interface which is causing issue. Why this is happening and how can I fix it or how to restore the memory?

Thanks.

Upvotes: 4

Views: 2431

Answers (2)

Ievgen
Ievgen

Reputation: 4443

Try to limit your image height. You can set DecodePixelHeight property to BitmapImage. It will take some time to convert you bytes but max height will be limited and memory usage will be reduced.

                var bmpImg = new BitmapImage();
                msImage.Position = 0;
                bmpImg.BeginInit();

                 bmpImg.DecodePixelHeight =containerHeight; 

                bmpImg.CacheOption = BitmapCacheOption.OnLoad;
                bmpImg.StreamSource = msImage;
                bmpImg.EndInit();
                return bmpImg;

P.s. Maybe you will have a memory leak there. http://code.logos.com/blog/2008/04/memory_leak_with_bitmapimage_and_memorystream.html

Upvotes: 0

Ben
Ben

Reputation: 1043

From the help my guess is that it creates a copy to cache it, and maybe one copy scaled down to use it on the button. And while the GC doesn't collect all the data that copied into the streams there will be multiple copies in the memory.

Upvotes: 1

Related Questions