460

For a WPF application which will need 10 - 20 small icons and images for illustrative purposes, is storing these in the assembly as embedded resources the right way to go?

If so, how do I specify in XAML that an Image control should load the image from an embedded resource?

11 Answers 11

521

If you will use the image in multiple places, then it's worth loading the image data only once into memory and then sharing it between all Image elements.

To do this, create a BitmapSource as a resource somewhere:

<BitmapImage x:Key="MyImageSource" UriSource="../Media/Image.png" />

Then, in your code, use something like:

<Image Source="{StaticResource MyImageSource}" />

In my case, I found that I had to set the Image.png file to have a build action of Resource rather than just Content. This causes the image to be carried within your compiled assembly.

Sign up to request clarification or add additional context in comments.

7 Comments

Would it be possible to do this dynamically? If I have a differing number of images that I would like to load on start-up, could I create a BitmapSource per image and refer to them the same way as above?
@Becky - Yes you could, though if you wanted to refer to them in Xaml then you might need to use the DynamicResource markup extension instead of StaticResource, assuming you would know the keys at compile time. In WPF you can create resource dictionaries at runtime. In fact, that's what happens when you load a Xaml document, it's just that you don't see the equivalent C#.
Something I hit: if you add your image resource to a resource dictionary, don't forget to refer to that image dictionary in the XAML for your component. Something like: <UserControl.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="Dictionary1.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </UserControl.Resources>
I usually add Width="{Binding Source.PixelWidth, RelativeSource={RelativeSource Self}}" to the Image, as otherwise I often see images getting grotesquely scaled up for some reason (such as 16x16 icons stretched to something that looks like 200x200 pixels).
I found that if the BitmapImage is declared in a referenced assembly's resourcedictionary, the UriSource needs to be a packURI for this to work. Otherwise, you will find that you can see the image in your xaml editor in VS but no image when debugging. Pack URIS: msdn.microsoft.com/en-au/library/aa970069(v=vs.100).aspx
|
208

I found to be the best practice of using images, videos, etc. is:

  • Change your files "Build action" to "Content". Be sure to check Copy to build directory.
    • Found on the "Right-Click" menu at the Solution Explorer window.
  • Image Source in the following format:
    • "/«YourAssemblyName»;component/«YourPath»/«YourImage.png»"

Example

<Image Source="/WPFApplication;component/Images/Start.png" />

Benefits:

  • Files are not embedded into the assembly.
    • The Resource Manager will raise some memory overflow problems with too many resources (at build time).
  • Can be called between assemblies.

11 Comments

This same approach works if you embed the resource in the assembly, but you have to set the "Build Action" to "Resource".
Works, thanks. One note for others: "component" is required "as is", "Images" is a relative path of png in the project. I.e. image that is placed in the root will be "<Image Source="/WPFApplication;component/Start.png" />"
An example of how to do this in C# would be nice. (That is not a valid URI so it can't be used when constructing a BitmapImage.)
So, how do you do it if the file is set to Embedded Resource? This doesn't seem to work. And I don't want to include the image in my project twice. (I'm already using it as an embedded resource.)
Where and how does "component" come into the path. Is that part of some specification?
|
53

In code to load a resource in the executing assembly where my image Freq.png was in the folder Icons and defined as Resource:

this.Icon = new BitmapImage(new Uri(@"pack://application:,,,/" 
    + Assembly.GetExecutingAssembly().GetName().Name 
    + ";component/" 
    + "Icons/Freq.png", UriKind.Absolute)); 

I also made a function:

/// <summary>
/// Load a resource WPF-BitmapImage (png, bmp, ...) from embedded resource defined as 'Resource' not as 'Embedded resource'.
/// </summary>
/// <param name="pathInApplication">Path without starting slash</param>
/// <param name="assembly">Usually 'Assembly.GetExecutingAssembly()'. If not mentionned, I will use the calling assembly</param>
/// <returns></returns>
public static BitmapImage LoadBitmapFromResource(string pathInApplication, Assembly assembly = null)
{
    if (assembly == null)
    {
        assembly = Assembly.GetCallingAssembly();
    }

    if (pathInApplication[0] == '/')
    {
        pathInApplication = pathInApplication.Substring(1);
    }
    return new BitmapImage(new Uri(@"pack://application:,,,/" + assembly.GetName().Name + ";component/" + pathInApplication, UriKind.Absolute)); 
}

Usage (assumption you put the function in a ResourceHelper class):

this.Icon = ResourceHelper.LoadBitmapFromResource("Icons/Freq.png");

Note: see MSDN Pack URIs in WPF:
pack://application:,,,/ReferencedAssembly;component/Subfolder/ResourceFile.xaml

8 Comments

new Uri throws Invalid URI: Invalid port specified.
Do you have the offending uri?
same uri as yours except that mine was running inside a winform hosted WPF. And the "pack" schema was not registered yet when I called new Uri.
Oops... it's probably retated to winform hosted WPF. I'm sorry. I won't try to fix it because I think it is not a very common usage. Good luck!
In my case, using new Uri(@"pack://application:,,,/" + pathInApplication) also did the trick.
|
49

Some people are asking about doing this in code and not getting an answer.

After spending many hours searching I found a very simple method, I found no example and so I share mine here which works with images. (mine was a .gif)

Summary:

It returns a BitmapFrame which ImageSource "destinations" seem to like.

Use:

doGetImageSourceFromResource ("[YourAssemblyNameHere]", "[YourResourceNameHere]");

Method:

static internal ImageSource doGetImageSourceFromResource(string psAssemblyName, string psResourceName)
{
    Uri oUri = new Uri("pack://application:,,,/" +psAssemblyName +";component/" +psResourceName, UriKind.RelativeOrAbsolute);
    return BitmapFrame.Create(oUri);
}

Learnings:

From my experiences the pack string is not the issue, check your streams and especially if reading it the first time has set the pointer to the end of the file and you need to re-set it to zero before reading again.

I hope this saves you the many hours I wish this piece had for me!

Comments

48

Yes, it is the right way.

You could use the image in the resource file just using the path:

<Image Source="..\Media\Image.png" />

You must set the build action of the image file to "Resource".

2 Comments

Thanks for this. Is there a way to do something similar with an ImageSource, essentially loading the image once into a resource dictionary. I fear that this approach loads the image data multiple times in memory.
This will be a mess when you need to refactor your code. You will have to manually change all the image references if your xaml document happens to change namespace. The method described by Drew Noakes is a lot smoother and maintable.
14

Full description how to use resources: WPF Application Resource, Content, and Data Files

And how to reference them, read "Pack URIs in WPF".

In short, there is even means to reference resources from referenced/referencing assemblies.

1 Comment

The link appears to be live and well (though it says "This documentation is archived and is not being maintained.").
8
  1. Visual Studio 2010 Professional SP1.
  2. .NET Framework 4 Client Profile.
  3. PNG image added as resource on project properties.
  4. New file in Resources folder automatically created.
  5. Build action set to resource.

This worked for me:

<BitmapImage x:Key="MyImageSource" UriSource="Resources/Image.png" />

Comments

4

If you're using Blend, to make it extra easy and not have any trouble getting the correct path for the Source attribute, just drag and drop the image from the Project panel onto the designer.

Comments

2

Yes, it's the right way. You can use images in the Resource file using a path:

<StackPanel Orientation="Horizontal">
    <CheckBox  Content="{Binding Nname}" IsChecked="{Binding IsChecked}"/>
    <Image Source="E:\SWorking\SharePointSecurityApps\SharePointSecurityApps\SharePointSecurityApps.WPF\Images\sitepermission.png"/>
    <TextBlock Text="{Binding Path=Title}"></TextBlock>
</StackPanel>

Comments

2

Building on the answer by Drew Noakes, here are the complete steps I followed to create a resource dictionary, add a BitmapImage resource to it, and reference the BitmapImage resource in a user control.

  1. Add an Images folder at the project root.
  2. Add MyImage.png under the Images folder.
  3. In the MyImage.png Properties window, set Build Action to Resource.
  4. Create a resource dictionary at the project root named MainResourceDictionary.xaml:
<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <BitmapImage x:Key="MyImageSource" UriSource="Images/MyImage.png" />
</ResourceDictionary>
  1. Add a reference to the resource dictionary in the control:
<UserControl ...>
    <UserControl.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="MainResourceDictionary.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </UserControl.Resources>
    ...
  1. Reference the image resource in the control:
<UserControl ...>
    <UserControl.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="MainResourceDictionary.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </UserControl.Resources>
    ...
    <Image Source="{DynamicResource ResourceKey=ServiceLevel1Source}" />
    ...

Comments

-4

The following worked and the images to be set is resources in properties:

    var bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(MyProject.Properties.Resources.myImage.GetHbitmap(),
                                      IntPtr.Zero,
                                      Int32Rect.Empty,
                                      BitmapSizeOptions.FromEmptyOptions());
    MyButton.Background = new ImageBrush(bitmapSource);
img_username.Source = bitmapSource;

1 Comment

No offence but this smells like bad practice.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.