ImageSource from String not working?

11,936

Solution 1

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

Solution 2

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"));
Share:
11,936
user1189352
Author by

user1189352

Updated on June 27, 2022

Comments

  • user1189352
    user1189352 almost 2 years

    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?

  • user1189352
    user1189352 about 10 years
    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!!
  • Clemens
    Clemens about 10 years
    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(...));.
  • Hamlet Hakobyan
    Hamlet Hakobyan about 10 years
    @Clemens, This is general type of initialization where you can tune the BitmpSource between BeginInit anf EndInit which is impossible in bitmap constuctor initialization.
  • Clemens
    Clemens about 10 years
    @HamletHakobyan Yes, but that isn't necessary here. Keep it simple.