12

I have some images added to my solution, right now it is under the folder images\flowers\rose.png inside the solution explorer. I want a way to dynamically load this image to my image control.

My current approach is making the type 'content' and use 'copy always' properties. Then i would give relative path to the image like below.

Image2.Source = new BitmapImage(new Uri("/images/flowers/Customswipe_b.png", UriKind.Relative));

Is there any way to make it load from the resource without copying it to the target system.

DeshDeep Singh
  • 1,817
  • 2
  • 23
  • 43
logeeks
  • 4,849
  • 15
  • 62
  • 93

3 Answers3

20

The following works just fine for me:

image.Source = new BitmapImage(new Uri("pack://application:,,,/YourAssemblyName;component/Resources/someimage.png", UriKind.Absolute));

Also you should change the Build Action of your image from None to Resource.

erikvimz
  • 5,256
  • 6
  • 44
  • 60
8

You can open the Resource Editor (Solution Explorer, click on Resources.resx) and add the image there. Then you can simply access it as Bitmap with Properties.Resources.ImageId

http://msdn.microsoft.com/en-us/library/3bka19x4(v=vs.100).aspx

MrDosu
  • 3,427
  • 15
  • 18
6

I had some problems to find the exact syntax for the URI, so see below more details :

If your image (myImage.png) is located in a subfolder "images" (from the root directory) , the exact syntax is :

image.Source = new BitmapImage(new Uri(@"pack://application:,,,/images/myImage.png", UriKind.Absolute));

If your image is in the subfolder images/icon/ (from the root directory) , the syntax is :

image.Source = new BitmapImage(new Uri(@"pack://application:,,,/images/icon/myImage.png", UriKind.Absolute));
  • Note that the part "pack://application:,,, does not change.
  • Be sure to set the "Build action" to "Resources"

For more information: see here.

Malick
  • 6,252
  • 2
  • 46
  • 59