【问题标题】:WPF load image from folderWPF从文件夹加载图像
【发布时间】:2014-03-26 13:03:16
【问题描述】:

我的图像不在资源中,而是在磁盘上。该文件夹与应用程序相关。我用过:

Overview_Picture.Source = new BitmapImage(new Uri(String.Format("file:///{0}/../MyImages /myim.jpg", Directory.GetCurrentDirectory())));
Overview_Picture.Source = new BitmapImage(uriSource);

但是这些类型的代码会产生很多问题,并且会弄乱 GetCurrentDirectory 返回的结果,有时可以,有时不能。

所以,MyImages 文件夹位于 Debug 文件夹旁边,我怎样才能在那里使用它们而不是像我一样,以其他更正确的方式使用它们?

【问题讨论】:

    标签: c# wpf xaml


    【解决方案1】:

    正如在 SO 中经常提到的,GetCurrentDirectory 方法根据定义并不总是返回您的程序集所在的目录,而是返回当前的工作目录。两者差别很大。

    您需要的是当前程序集文件夹(及其父文件夹)。另外,我不确定是否希望图片是安装文件夹上方的一个文件夹(这基本上就是您说它们比Debug 文件夹高一级时所说的 - 在现实生活中会是应用程序安装到的文件夹上方的一个文件夹)。

    使用以下内容:

    string currentAssemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
    string currentAssemblyParentPath = Path.GetDirectoryName(currentAssemblyPath);
    
    Overview_Picture.Source = new BitmapImage(new Uri(String.Format("file:///{0}/MyImages/myim.jpg", currentAssemblyParentPath)));
    

    另外,MyImages 之后还有一个杂散空间 ,我将其删除。

    【讨论】:

      【解决方案2】:

      从相对文件路径构造绝对 Uri 的替代方法是仅从相对路径打开 FileStream,并将其分配给 BitmapImage 的 StreamSource 属性。但请注意,当您想在初始化 BitmapImage 后立即关闭流时,还必须设置 BitmapCacheOption.OnLoad

      var bitmap = new BitmapImage();
      
      using (var stream = new FileStream("../MyImages/myim.jpg", FileMode.Open))
      {
          bitmap.BeginInit();
          bitmap.CacheOption = BitmapCacheOption.OnLoad;
          bitmap.StreamSource = stream;
          bitmap.EndInit();
          bitmap.Freeze(); // optional
      }
      
      Overview_Picture.Source = bitmap;
      

      【讨论】:

        猜你喜欢
        • 2013-04-10
        • 1970-01-01
        • 2012-07-28
        • 2012-08-24
        • 1970-01-01
        • 1970-01-01
        • 2011-07-07
        • 2015-08-30
        • 2016-05-28
        相关资源
        最近更新 更多