Saving ImageSource (BitmapSource) in XML

后端 未结 1 1910
粉色の甜心
粉色の甜心 2021-01-16 07:49

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 o

相关标签:
1条回答
  • 2021-01-16 08:20

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题