user4470962
user4470962

Reputation:

How to set source for Image Control where the image resides in application folder

I am using an image control. i am setting the source for Image control like below.

But the error shows invalid URI.

 string strUri = String.Format(@"..\..\Assets\Images\Image001.jpeg"); 
  previewImage.Source = BitmapFromUri(new Uri(strUri));

 public static ImageSource BitmapFromUri(Uri source)
    {
        var bitmap = new BitmapImage();
        bitmap.BeginInit();
        bitmap.UriSource = source;
        bitmap.CacheOption = BitmapCacheOption.OnLoad;
        bitmap.EndInit();
        return bitmap;
    }

Upvotes: 2

Views: 188

Answers (1)

Clemens
Clemens

Reputation: 128061

You'll have to specify that it is a relative URI by setting UriKind.Relative:

var uri = new Uri(@"..\..\Assets\Images\Image001.jpeg", UriKind.Relative);

That said, your BitmapFromUri method might be redundant (unless you have a reason to set BitmapCacheOption.OnLoad). You may probably as well use the BitmapImage constructor that takes an Uri parameter:

previewImage.Source = new BitmapImage(uri);

Please note also that the above assumes that image file is actually copied to the specified relative path. If it is part of your Visual Studio project, it might perhaps better be loaded as embedded resource via a WPF Pack URI. You would therefore have to set its Build Action to Resource.

Upvotes: 1

Related Questions