1

I have a Bitmap list where I store some images. Then I want an Image element on a WPF UserControl to be the first element of that list. For that I tried this:

Image2.Source = myBitmapArray[0].ToBitmapImage();

Where ToBitmapImage is a static function that looks like this:

public static BitmapImage ToBitmapImage(this Bitmap bitmap)
    {
        BitmapImage bitmapImage = new BitmapImage();

        using (MemoryStream memoryStream = new MemoryStream())
        {
            bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
            memoryStream.Position = 0;
            bitmapImage.BeginInit();
            bitmapImage.StreamSource = memoryStream;
            bitmapImage.EndInit();
        }

        return bitmapImage;
    }

But when I assign the BitmapImage to my Image.Source it doesn't show the image. What I'm doing wrong?

Sonhja
  • 8,230
  • 20
  • 73
  • 131

1 Answers1

3

You are disposing the MemoryStream after assigning it to the StreamSource property.

But accoding to BitmapImage.StreamSource you have to

set the CacheOption property to BitmapCacheOption.OnLoad if you wish to close the stream after the BitmapImage is created. The default OnDemand cache option retains access to the stream until the bitmap is needed, and cleanup is handled by the garbage collector.

So either drop the using statement so the MemoryStream won't be disposed or use the BitmapCacheOption.OnLoad.

Dirk
  • 10,668
  • 2
  • 35
  • 49