【问题标题】:Change image source in code behind - Wpf在后面的代码中更改图像源 - Wpf
【发布时间】:2010-09-24 12:42:48
【问题描述】:

我需要动态设置图片来源,请注意我的图片在网络的某个地方,这是我的代码

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 前缀无法识别

【问题讨论】:

    标签: c# wpf imagesource


    【解决方案1】:

    以上解决方案都不适合我。但这确实:

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

    【讨论】:

    • +1 因为最近。这也是唯一对我有用的东西。
    • 请注意,这在 UWP 中不起作用,因为 UWP 似乎只接受绝对 URI。我是这样做的:myImage.Source = new BitmapImage (new Uri (new Uri (Directory.GetCurrentDirectory(), UriKind.Absolute), new Uri (@"/Images/foo.png", UriKind.Relative)));
    • 这可能无法回答问题,但由于我的问题将我带到这里,所以这个答案对我有用。
    • 我遇到的唯一问题是png的透明度丢失了,似乎没有办法恢复它......
    【解决方案2】:

    你只需要一行:

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

    【讨论】:

      【解决方案3】:

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

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

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

      【讨论】:

        【解决方案4】:

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

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

        【讨论】:

          【解决方案5】:

          你们都错了! 为什么?因为您只需要这段代码即可工作:

          (image View) / C# Img is : your Image box

          保持原样,无需更改 ("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"));
              }
          

          【讨论】:

          • 我会说你们都错了,因为你们都没有提供完整的工作示例。只是假设读者知道在代码中放置这些 sn-ps 的位置。
          • 答案开头的轻率评论是不必要的。完整的工作答案,以及如何使用的说明都是必需的。
          猜你喜欢
          • 1970-01-01
          • 2010-12-30
          • 1970-01-01
          • 2016-11-12
          • 2023-04-02
          • 1970-01-01
          • 2016-05-02
          • 2010-10-20
          • 1970-01-01
          相关资源
          最近更新 更多