wpf 来自 String 的 ImageSource 不起作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22207114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 11:08:10  来源:igfitidea点击:

ImageSource from String not working?

c#wpfimageimagesource

提问by user1189352

I have a bunch of *.tif images in a folder in my project..which i've also added to my visual studio project in a folder located "Templates\Team Logos"

我的项目中的文件夹中有一堆 *.tif 图像。

now if i set an image source to say:

现在,如果我将图像源设置为:

<Image Name="UL_Team1_Image" Grid.Row="1" Grid.Column="1" Margin="5" Source="Team Logos\ARI.tif"></Image>

That works. But now if i try:

那个有效。但现在如果我尝试:

UL_ImageArr[a].Source = (ImageSource)new ImageSourceConverter().ConvertFromString("Team Logos\ARI.tif");

that doesn't work. What gives? I get a NullReferenceException... but it doesn't make sense to me?

那行不通。是什么赋予了?我得到一个 NullReferenceException ......但对我来说没有意义?

回答by Hamlet Hakobyan

You can use this in your code-behind, I think, it is more faster than using ImageSourceConverter.

您可以在代码隐藏中使用它,我认为它比使用ImageSourceConverter.

BitmapImage bimage = new BitmapImage();
bimage.BeginInit();
bimage.UriSource = new Uri("Team Logos\ARI.tif", UriKind.Relative);
bimage.EndInit();
UL_ImageArr[a].Source = bimage

If you want to use ImageSourceConverteryou must refer to image file by pack-uri:

如果要使用ImageSourceConverter,必须通过pack-uri引用图像文件:

var converter = new ImageSourceConverter();
UL_ImageArr[a].Source = 
         (ImageSource)converter.ConvertFromString("pack://application:,,,/Team Logos/ARI.tif");

回答by Clemens

In code behind you will usually write the full pack URIto reference image resources.

在后面的代码中,您通常会编写完整的包 URI来引用图像资源。

So you either write

所以你要么写

UL_ImageArr[a].Source = (ImageSource)new ImageSourceConverter().ConvertFromString(
                        "pack://application:,,,/Team Logos/ARI.tif");

or

或者

UL_ImageArr[a].Source = new BitmapImage(new Uri(
                        "pack://application:,,,/Team Logos/ARI.tif"));

or

或者

UL_ImageArr[a].Source = BitmapFrame.Create(new Uri(
                        "pack://application:,,,/Team Logos/ARI.tif"));

回答by Daniel

If you are on WinRt, use this

如果您在WinRt 上,请使用此

string url = "ms-appx:///Assets/placeHolder.png";
return new BitmapImage(new Uri(url));