3

I would like to use path to image from program resources instead of using full path from windows.

tlo.Fill = new ImageBrush
{
  ImageSource = new BitmapImage(new Uri(@"D:\Willie\Documents\ColorTester\ColorTester\Resources\1.jpg", UriKind.Absolute))
};

I want to use path like this:

ImageSource = new BitmapImage(new Uri("ColorTester.Resources.1.jpg"));

Can anyone help me with this, because when I try to use it, visual studio throws and exception "System.UriFormatException"?

1 Answers1

0

I don't know the correct path to your image, if you have a folder named Resources under your project and images are in there, you can address them like below:

ImageSource = new BitmapImage(new Uri("/Resources/1.jpg", UriKind.Relative));

If the image is inside a UserControl and you want to use it in another project, then address it like:

ImageSource = new BitmapImage(new Uri("pack://application:,,,/{YourAssemblyWhereResourceIsLocated};component/Resources/1.jpg"));

Useful links:

  • When I try the first option this exception pops "Invalid URI: The format of the URI could not be determined." Edit: This worked for me: ImageSource = new BitmapImage(new Uri(@"pack://application:,,,/Resources/1.jpg")); –  Jun 30 '19 at 08:46
  • You always have to use a full Pack URI, including the `pack://application:,,,` prefix in code behind. As opposed to XAML, where the XAML parser automatically adds it. – Clemens Jun 30 '19 at 13:32
  • @Clemens But in "Using Pack URIs in Code" section of https://learn.microsoft.com/en-us/dotnet/framework/wpf/app-development/pack-uris-in-wpf it uses Relative URI without pack://application:,,, prefix – Saman Hakimzadeh Abyaneh Jul 01 '19 at 08:29
  • "you have to" is perhaps not exactly true, but the relative syntax is totally confusing, since you can't actually see what the URI is supposed to reference. It might as well be a relative file path. You should simply avoid that syntax. Even if it somehow happens to work. – Clemens Jul 01 '19 at 08:34