1

I am trying to fill a rectangle with an image, the image is stored in a folder Images in the root of my project. So BrushesAndPens/Images/oog.png

Now when I add the image to a rectangle via Xaml this works fine but when I do it dynamically it finds the path but after that throws an Exception error. Code and error below. I am pretty sure my code is correct and the the image is in the correct folder.

The code:

 ImageBrush imgBrush = new ImageBrush();
 imgBrush.ImageSource = new BitmapImage(new Uri(@"Images/oog.png", UriKind.Relative));
 Rect6.Fill = imgBrush;

The Exception:

ExceptionImageLINK

PIETER BRACKE
  • 25
  • 1
  • 7
  • Image files should usually be assembly resources. Just add them to your Visual Studio project and make sure their Build Action is set to Resource (which should be set by default). See the edited answer for an explanation how these are loaded in code behind. – Clemens Apr 01 '18 at 19:45

1 Answers1

2

If the image file is an assembly resource, i.e. the Build Action of the file in your Visual Studio project is set to Resource, it has to be loaded by a Resource File Pack URI. While in XAML the URI prefix is added automatically, you'll have to write it explicitly in code behind:

imgBrush.ImageSource = new BitmapImage(new Uri("pack://application:,,,/Images/oog.png"));
Clemens
  • 123,504
  • 12
  • 155
  • 268
Software Dev
  • 5,368
  • 5
  • 22
  • 45
  • Ok, I'll try that so it is not possible to add the imageSource directly to the te Brush and then add the brush to the fill of the rectangle? – PIETER BRACKE Apr 01 '18 at 12:26
  • yes it is possible...just use the uri/path as follows : `pack://application:,,,/ur assembly name here;component/Images/oog.png` – Software Dev Apr 01 '18 at 12:27
  • Ok thx I used my own code but had to change the Uri path to the "pack://application:,,,/PensAndBrushes;component/Images/oog.png" How come the regular Images/oog.png doesn't work if I may ask? – PIETER BRACKE Apr 01 '18 at 12:34
  • wait....where is `Images/oog.png` exactly ?? the URI i provided will work only if the image is in resource .. is it in resource ? – Software Dev Apr 01 '18 at 12:36
  • I basically just created a folder Images in my project and added existing item oog.png. Didn't realize I needed to add it as a resource 2 if i added it to the project. – PIETER BRACKE Apr 01 '18 at 12:41
  • no u dont necessarily need to add them to resource ... just tell me this : is the `Imges` folder inside debug folder ? or inside the folder the app launches from ? – Software Dev Apr 01 '18 at 12:43
  • It's in the folder the app launches from, The path on my hard drive is following C:\Users\Pieter\Documents\Visual Studio 2017\Projects\BrushesAndPens\BrushesAndPens\Images – PIETER BRACKE Apr 01 '18 at 12:45
  • then just use this as the uri `System.IO.GetCurrentDirectory +@"Images/org.png"` , thts all – Software Dev Apr 01 '18 at 12:47