1

I am using MemoryStram for converting Bitmap to BitmapImage and when I checked the CPU usage it is consuming more memory. I wanted to reduce the memory consumption of MemoryStream object. I used it in Using statement also and the result is same as earlier mentioned. 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;
}
Ganesh
  • 195
  • 7
  • 1
    It looks like you could omit the memorystream, and also the call to `ToArray` by feeding the result of `Bitmap.Save` directly into the `bImg.StreamSource`? – Cee McSharpface Jul 20 '18 at 14:36

1 Answers1

3

There is no need for a second 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():

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, e.g. this: fast converting Bitmap to BitmapSource wpf

Clemens
  • 123,504
  • 12
  • 155
  • 268
  • Thanks for help, the given link **fast converting Bitmap to BitmapSource wpf** is giving better performance. – Ganesh Jul 20 '18 at 15:46