Search code examples
c#wpfblend

Load image from specific file


How can I set the ImageSource to be an image from a specific folder?

I tried moving the image in Debug and running the following code:

image.Source = new BitmapImage(new Uri("kafpodhlato.png"));

But I get the following error:

An unhandled exception of type 'System.UriFormatException' occurred in System.dll

Additional information: Invalid URI: The format of the URI could not be determined.

EDIT: Creating a folder named Resources, setting its Build action to Resource and then using the following code solved my problem.

image.Source = new BitmapImage(new Uri(@"pack://application:,,,/Resources/panamaxi.png"));

Solution

  • This should work:

    image.Source = new BitmapImage(new Uri("kafpodhlato.png", UriKind.Relative));
    

    You may however want to load the image from an assembly resource by a Pack URI.

    Add the image file to your Visual Studio project, e.g. to a folder named Images. Then set its Build Action to Resource, and load it by

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