问题描述
我正在尝试在XML文件中保存并加载 ImageSource
(或 BitmapSource
)。快速查看SO给了我。
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;
似乎没有任何错误或例外。在单步执行代码 BackgroundImage
时,看起来它被设置为有效的图像对象。
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.
我的WPF表单有一个图像控件,它的源绑定到一个属性,该属性返回 BackgroundImage
属性的结果。我猜测绑定工作正常,因为第一个测试按预期工作。
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?
推荐答案
来自。 指出使用默认 OnDemand
缓存选项在实际使用图像之前,不得关闭流。在你的情况下,这意味着 Image
元素正在尝试访问已经处理好的流。
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.
修复很漂亮很简单,你只需要将缓存选项更改为 OnLoad
,问题就消失了:
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);
}
}
这篇关于以XML格式保存ImageSource(BitmapSource)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!