Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading images in WPF from code

Tags:

c#

.net

wpf

I must have read tons of solutions online, but for some idiotic reason I can not get them to work.

I have a .jpg image in the Resources folder of my project, and the image is set to Build Action: Resource (not embedded resource) and never copy to output folder. My image is not added to my resources.resx file.

I am trying to access the file like so:

lResult = new BitmapImage(new Uri(@"pack://application:,,,/Resources/ImageMissing.jpg", UriKind.Absolute));

But this fails saying that there is no image there.

This is so basic I feel really stupid, but I just cannot seem to grasp the simple concept of resources usage.

Thank you.

like image 781
So Many Goblins Avatar asked May 12 '11 18:05

So Many Goblins


2 Answers

If you need to specify that the resource being referred to is referenced from the local assembly, then I would think that you would want to include "component". For example, I have some code that loads an icon from a resource available from the same assembly in which my code resides. I write this:

var SourceUri = new Uri("pack://application:,,,/MyCompany.MyProduct.MyAssembly;component/MyIcon.ico", UriKind.Absolute);
thisIcon = new BitmapImage(SourceUri);

As noted in the article available at http://msdn.microsoft.com/en-us/library/aa970069.aspx, the following additional examples illustrate the use of "component":

The following example shows the pack URI for a XAML resource file that is located in the root of the referenced assembly's project folder.

pack://application:,,,/ReferencedAssembly;component/ResourceFile.xaml

The following example shows the pack URI for a XAML resource file that is located in a subfolder of the referenced assembly's project folder.

pack://application:,,,/ReferencedAssembly;component/Subfolder/ResourceFile.xaml

The following example shows the pack URI for a XAML resource file that is located in the root folder of a referenced, version-specific assembly's project folder.

pack://application:,,,/ReferencedAssembly;v1.0.0.1;component/ResourceFile.xaml

Note that the pack URI syntax for referenced assembly resource files can be used only with the application:/// authority. For example, the following is not supported in WPF.

pack://siteoforigin:,,,/SomeAssembly;component/ResourceFile.xaml
like image 186
JeffFerguson Avatar answered Oct 04 '22 10:10

JeffFerguson


You need one more comma in there. Here is the documentation on Pack URIs in WPF. Notice there are three commas when using the authority.

lResult = new BitmapImage(new Uri(@"pack://application:,,,/Resources/ImageMissing.jpg", UriKind.Absolute));
like image 33
CodeNaked Avatar answered Oct 04 '22 11:10

CodeNaked