Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load Image at runtime from resource in WPF

Tags:

wpf

Im trying to load a image at runtime in WPF using the following code

_image = new Image();
BitmapImage src = new BitmapImage();
src.BeginInit();
src.UriSource = new Uri(@"pack://application:,,,/images/tagimages/placeholder.png", UriKind.Absolute);                
src.CacheOption = BitmapCacheOption.OnLoad;
src.EndInit();
_image.Source = src;
_image.Stretch = Stretch.None;

In my project I have a folder called images and a sub folder of that folder called tagimages that contains the placeholder.png. When I run this code I get the following error

"Cannot locate resource 'images/tagimages/placeholder.png'"

What am I doing wrong?

like image 767
John Avatar asked Mar 20 '12 10:03

John


2 Answers

It turns out that I should have used

Uri(@"pack://application:,,,/<MyProject>;component/images/tagimages/placeholder.png", UriKind.Absolute);
like image 138
John Avatar answered Oct 14 '22 06:10

John


From procedural code you use: @"pack://application:,,,/putyourfilenamehere" for an embedded resource.

Or in other words

BitmapImage image = new BitmapImage(new Uri("pack://application:,,,/Images/myimage.png"));

like image 37
Epirocks Avatar answered Oct 14 '22 06:10

Epirocks