C#中如何从相对URL获取图片,图片不能在项目中

发布于 2024-08-30 03:19:58 字数 623 浏览 3 评论 0原文

我有一个项目,我从 xml 文件加载相对图像 Uri。 我正在像这样加载图像:

if (child.Name == "photo" &&
    child.Attributes["href"] != null &&
    File.Exists(child.Attributes["href"].Value))
{
    Image image = new Image();
    image.Source = new BitmapImage(new Uri(child.Attributes["href"].Value, UriKind.RelativeOrAbsolute));
    images.Add(image);
}

其中“子”对象是一个 XmlNode,它可能看起来像这样

<photo name="info" href="Resources\Content\test.png"/>

在调试过程中,图像似乎充满了实际图像,但当我想以任何方式查看它们时,它什么也没有显示。 奇怪的是,当我在项目中包含图像时,它确实可以工作,但是我不想这样做,因为我使用 xml 文件的观点是这样它就会丢失,因为在更改后无论如何你都必须重建程序。

I have a project where I'm loading relative image Uri's from an xml file.
I'm loading the image like this:

if (child.Name == "photo" &&
    child.Attributes["href"] != null &&
    File.Exists(child.Attributes["href"].Value))
{
    Image image = new Image();
    image.Source = new BitmapImage(new Uri(child.Attributes["href"].Value, UriKind.RelativeOrAbsolute));
    images.Add(image);
}

Where the "child" object is an XmlNode which could looks like this

<photo name="info" href="Resources\Content\test.png"/>

During debug it seemd images is filled with actual images but when I want to see them in any way it shows nothing.
Weird thing is when I include the images in my project it does work, I however dont want to do that since my point for using an xml file is so that it would be lost since you'd have to rebuild the program anyway after a change.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

苦笑流年记忆 2024-09-06 03:19:58

这不是完美的解决方案,但它仍然有效,我将相对 Uri 转换为绝对 Uri,如下所示

if (child.Name == "photo" &&
    child.Attributes["href"] != null &&
    File.Exists(Environment.CurrentDirectory + child.Attributes["href"].Value))
{
    Image image = new Image();
    image.Source = new BitmapImage(new Uri(Environment.CurrentDirectory + child.Attributes["href"].Value, UriKind.RelativeOrAbsolute));
    images.Add(image);
}

只需更改 xml 中的所有 Uri 以具有前导斜杠。

Not the perfect solution but its works nonetheless, I'm converting the relative Uri's to absolute ones like this

if (child.Name == "photo" &&
    child.Attributes["href"] != null &&
    File.Exists(Environment.CurrentDirectory + child.Attributes["href"].Value))
{
    Image image = new Image();
    image.Source = new BitmapImage(new Uri(Environment.CurrentDirectory + child.Attributes["href"].Value, UriKind.RelativeOrAbsolute));
    images.Add(image);
}

Only had to change all the Uri's in the xml to have a leading slash.

灰色世界里的红玫瑰 2024-09-06 03:19:58

嗯,可能是这个简单的当前文件夹问题。 VS检查project/Resources/Content/文件夹下的资源,程序检查project/bin/Debug/Resources/Content/文件夹下的资源。

Hmm can be this simple current folder problem. VS check resources under project/Resources/Content/ folder and program check resources under project/bin/Debug/Resources/Content/ folder.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文