2010-09-24 73 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; 
     }