WPF how do you load an image from the resources?

Category: c# general


herrabanani on Sat, 01 Mar 2014 19:59:33

in windforumapp you would just do it like this:

   img1.Image = Properties.Resources.image1;

but you can't do that in wpf.  you can only do img1.Source. how do you make an image in wpf use a resources image?


João Eduardo Sousa on Sun, 02 Mar 2014 00:05:50

To use a resource image in XAML, what you should actually do is set the build action for the image file to "Resource" (not "Embedded Resource", also don't add it to a .resx file). Then you can access the image from XAML with a pack:// url, e.g. (assuming the file is in a subdirectory of the project called Resources):
<Image Source="pack://application:,,/Resources/myfile.png" />

In code you could access it as follows:
BitmapImage img = new BitmapImage();
img.UriSource = new Uri("pack://application:,,/Resources/myfile.png");

And you can use the following extension function to convert GDI+ bitmaps to WPF BitmapSources:
public static BitmapSource ToBitmapSource(this System.Drawing.Bitmap bitmap)
    using( System.IO.MemoryStream stream )
        bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
        stream.Position = 0;

        var result = BitmapFrame.Create(stream, BitmapCreateOptions.None, BitmapCacheOptions.OnLoad);
        return result;

herrabanani on Sun, 02 Mar 2014 03:11:54

where exactly am i supposed to put this? i'm sorry i'm kidna new to programing in c#. if you could send me an example file useing this that would be AWESOME.

Ashish Pandey on Sun, 02 Mar 2014 03:36:04

Visit this link It may help you

string  bitmapPath = @"My%20Application;component/image1.png";
BitmapImage bitmapImage = new BitmapImage(new Uri(bitmapPath, UriKind.Relative));
pictureIcon.Source = bitmapImage; 


Ashish Pandey