【问题标题】:get absolute file path from image in WPF从WPF中的图像获取绝对文件路径
【发布时间】:2011-02-07 13:33:08
【问题描述】:

我的 xaml 中有类似的内容:

<Grid>
    <Image Name="image" Source="../../Images/DefaultImage.png" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"></Image>
</Grid>

如何(使用我的代码隐藏 C# 代码)获取图像源的绝对路径?

【问题讨论】:

    标签: wpf image bitmap


    【解决方案1】:

    每次都适合我的方法就是这条简单的线

    (YourImage.Source as BitmapImage).UriSource
    

    此外,您可以根据需要处理返回的 UriSource 的 AbsolutePath 或 AbsoluteUri。

    【讨论】:

      【解决方案2】:

      当从 Uri 字符串或文件名转换时,ImageConverter 创建一个 BitmapDecoder 并提取其第一个帧。应该可以通过以下方式获取 Uri:

      ((BitmapFrame)image.Source).Decoder.ToString()
      

      请注意,这通常会返回绝对 Uri,而不是在 XAML 中找到的原始 Uri。如果您需要 XAML 中的确切原始 Uri,可以在 BitmapDecoder 的 _uri 字段中找到它,但您需要反射和提升的代码权限才能获得它,而且您的代码可能无法在未来的 NET Framework 版本中运行。

      【讨论】:

        【解决方案3】:

        你可以试试这个:

        string path = ((BitmapImage)image.Source).UriSource.AbsolutePath;
        

        【讨论】:

        • 它不起作用。由于强制转换为 BitmapImage,我得到了一个异常
        • 强制位图图像是否可以接受?如:
        • 是的,如果我以这种方式声明图像,它应该可以工作,但我有不同的方式
        猜你喜欢
        • 2019-07-29
        • 1970-01-01
        • 2016-06-22
        相关资源
        最近更新 更多