3

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"

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?

3 Answers 3

6

You can use this in your code-behind, I think, it is more faster than using 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 ImageSourceConverter you must refer to image file by pack-uri:

var converter = new ImageSourceConverter();
UL_ImageArr[a].Source = 
    (ImageSource)converter.ConvertFromString("pack://application:,,,/Team Logos/ARI.tif");
Sign up to request clarification or add additional context in comments.

4 Comments

thanks it worked! just weird as i've used the convertfromstring feature for a different project and it worked just fine.. not sure why it didn't work for this project. anyway tyvm!!
Why so complicated? BitmapImage has a constructor that takes a Uri argument. That saves you the BeginInit and EndInit calls. Just write UL_ImageArr[a].Source = new BitmapImage(new Uri(...));.
@Clemens, This is general type of initialization where you can tune the BitmpSource between BeginInit anf EndInit which is impossible in bitmap constuctor initialization.
@HamletHakobyan Yes, but that isn't necessary here. Keep it simple.
5

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

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"));

Comments

-1

If you are on WinRt, use this

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.