gpt4 book ai didi

c# - 在 XML 中保存 ImageSource (BitmapSource)

转载 作者:太空宇宙 更新时间:2023-11-03 21:53:23 25 4
gpt4 key购买 nike

我正在尝试在 XML 文件中保存和加载 ImageSource(或 BitmapSource)。快速浏览 SO 给了我 this answer .

它看起来不错,所以我尝试了一下,但我得到了一个奇怪的结果。

当我尝试这段代码时,一切正常:

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

但是当我尝试这段代码时,图像根本就没有出现:

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 看起来像是被设置为一个有效的图像对象。

我的 WPF 表单有一个图像控件,它的源代码绑定(bind)到一个返回 BackgroundImage 属性结果的属性。我猜绑定(bind)工作正常,因为第一个测试按预期工作。

谁能帮我理解为什么第二个测试没有显示我的图像?

最佳答案

来自 this answerBase64ToImage 方法有问题. documentation声明使用默认的 OnDemand 缓存选项,在实际使用图像之前不得关闭流。在您的情况下,这意味着 Image 元素正在尝试访问已处理的流。

修复非常简单,您只需将缓存选项更改为OnLoad,问题就消失了:

BitmapSource Base64ToImage(string base64)
{
byte[] bytes = Convert.FromBase64String(base64);
using (var stream = new MemoryStream(bytes))
{
return BitmapFrame.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
}
}

关于c# - 在 XML 中保存 ImageSource (BitmapSource),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13423796/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com