2010-09-24 52 views
28

我需要動態設置圖像源,請注意我的形象在網絡上的某個地方,這裏是我的代碼更改圖像源的背後 - WPF

BitmapImage logo = new BitmapImage(); 
logo.BeginInit(); 
logo.UriSource = new Uri(@"pack://application:,,,\\myserver\\folder1\\Customer Data\\sample.png"); 
logo.EndInit(); // Getting the exception here 
ImageViewer1.Source = logo; 

例外:

的無法識別URI前綴

回答

47

你只需要一條線:

ImageViewer1.Source = new BitmapImage(new Uri(@"\myserver\folder1\Customer Data\sample.png")); 
+5

你並不需要,如果你使用原義字符串 – 2010-09-24 13:08:33

4

您在此處使用的數據包語法適用於在應用程序中作爲資源包含的圖像,而不是用於文件系統中的鬆散文件。

你只是想實際的路徑傳遞到UriSource:

logo.UriSource = new Uri(@"\\myserver\folder1\Customer Data\sample.png"); 
0

你們都錯了! 爲什麼?因爲所有你需要的是此代碼工作:

(圖像查看)/ C#圖是:你的圖片框

保持這個原樣,沒有變化(「MS-APPX:///)這是代碼不是你的應用程序名稱 形象是你在你的項目文件夾,你可以改變它。 dog.png是你的文件夾中的文件,以及我做我的文件夾「圖片」和文件「dog.png」 所以URI是: 「MS-APPX:///Images/dog.png」 和我的代碼:


private void Button_Click(object sender, RoutedEventArgs e) 
    { 
     img.Source = new BitmapImage(new Uri("ms-appx:///Images/dog.png")); 
    } 
+7

此代碼適用於Windows RT和Windows Phone,而不是WPF – Ali 2015-05-01 02:26:11

+1

逃避反斜槓@AymanSammoudi這不會對WPF工作 – 2017-01-11 09:18:15

51

上述解決方案都不適用於我。但這並:

myImage.Source = new BitmapImage(new Uri(@"/Images/foo.png", UriKind.Relative)); 
+4

+1,因爲這麼近。這也是唯一對我有用的東西。 – 2013-12-11 12:47:30

+0

!優秀和工作 – 2014-02-19 10:04:45

+2

請注意,這個_doesn't_在UWP工作,因爲UWP似乎只接受絕對URI。這裏是我如何做到:'myImage.Source = new BitmapImage(new Uri(new Uri(Directory.GetCurrentDirectory(),UriKind.Absolute),new Uri(@「/ Images/foo.png」,UriKind.Relative))) ;' – Thought 2017-04-01 23:30:36

2

的方法都沒有工作對我來說,我需要從一個文件夾拉圖像,而不是將它添加到應用程序。 下面的代碼工作:

TestImage.Source = GetImage("/Content/Images/test.png") 

private static BitmapImage GetImage(string imageUri) 
     { 
      var bitmapImage = new BitmapImage(); 
      bitmapImage.BeginInit(); 
      bitmapImage.UriSource = new Uri("pack://siteoforigin:,,,/" + imageUri,    UriKind.RelativeOrAbsolute); 
      bitmapImage.EndInit(); 
      return bitmapImage; 
     }