2

I am trying to save and load an ImageSource (or BitmapSource) to and from an XML file. A quick look on SO gave me this answer.

It looked ok so I tried it out but I am getting a strange result.

When I try this code everything works:

BitmapSource testImgSrc = new WriteableBitmap(new BitmapImage(new Uri("pack://application:,,,/MyNameSpace;component/Images/MyImg.png")));
BackgroundImage = testImgSrc;

But when I try this code the image just does not appear at all:

BitmapSource testImgSrc = new WriteableBitmap(new BitmapImage(new Uri("pack://application:,,,/MyNameSpace;component/Images/MyImg.png")));
string testImgStr = ImageToBase64(testImgSrc);
BitmapSource testImg = Base64ToImage(testImgStr);
BackgroundImage = testImg;

There don't seem to be any errors or exceptions. When steping through the code BackgroundImage looks like it gets set to a valid image object.

My WPF form has an image control that has it's source bound to a property that returns the result of the BackgroundImage property. I am guessing the binding is working ok because the first test works as expected.

Can anyone help me to understand why the second test is not displaying my image?

Community
  • 1
  • 1
Ben
  • 3,241
  • 4
  • 35
  • 49

1 Answers1

5

There's a problem with Base64ToImage method from this answer. The documentation states that with the default OnDemand cache option the stream must not be closed before the image is actually used. In your case this means that the Image element is trying to access the already disposed stream.

The fix is pretty simple, you just need to change the cache option to OnLoad and the problem is gone:

BitmapSource Base64ToImage(string base64)
{
    byte[] bytes = Convert.FromBase64String(base64);
    using (var stream = new MemoryStream(bytes))
    {
        return BitmapFrame.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
    }
}
Community
  • 1
  • 1
Damir Arh
  • 17,637
  • 2
  • 45
  • 83