在后面的代码中更改图像源 - Wpf

时间:2010-09-24 12:42:49

标签: c# wpf imagesource

我需要动态设置图像源,请注意我的图像位于网络上的某个位置,这是我的代码

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前缀

5 个答案:

答案 0 :(得分:63)

以上解决方案均不适合我。但这样做了:

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

答案 1 :(得分:61)

你只需要一行:

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

答案 2 :(得分:5)

您在此处使用的包语法是针对在您的应用程序中作为资源包含的图像,而不是文件系统中的松散文件。

您只想将实际路径传递给UriSource:

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

答案 3 :(得分:3)

这些方法都不适合我,因为我需要从文件夹中提取图像而不是将其添加到应用程序中。 以下代码有效:

 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;
        } 

答案 4 :(得分:-1)

你错了! 为什么?因为您只需要这个代码就可以了:

(图片查看)/ C#Img是:您的图片框

保持原样,不做任何更改(“ms-appx:///”)这不是您的应用名称代码 图像是项目中的文件夹,您可以更改它。 dog.png是你文件夹中的文件,以及我的文件夹'Images'和文件'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"));
    }
相关问题