【发布时间】:2011-02-07 13:33:08
【问题描述】:
我的 xaml 中有类似的内容:
<Grid>
<Image Name="image" Source="../../Images/DefaultImage.png" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"></Image>
</Grid>
如何(使用我的代码隐藏 C# 代码)获取图像源的绝对路径?
【问题讨论】:
我的 xaml 中有类似的内容:
<Grid>
<Image Name="image" Source="../../Images/DefaultImage.png" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"></Image>
</Grid>
如何(使用我的代码隐藏 C# 代码)获取图像源的绝对路径?
【问题讨论】:
每次都适合我的方法就是这条简单的线
(YourImage.Source as BitmapImage).UriSource
此外,您可以根据需要处理返回的 UriSource 的 AbsolutePath 或 AbsoluteUri。
【讨论】:
当从 Uri 字符串或文件名转换时,ImageConverter 创建一个 BitmapDecoder 并提取其第一个帧。应该可以通过以下方式获取 Uri:
((BitmapFrame)image.Source).Decoder.ToString()
请注意,这通常会返回绝对 Uri,而不是在 XAML 中找到的原始 Uri。如果您需要 XAML 中的确切原始 Uri,可以在 BitmapDecoder 的 _uri 字段中找到它,但您需要反射和提升的代码权限才能获得它,而且您的代码可能无法在未来的 NET Framework 版本中运行。
【讨论】:
你可以试试这个:
string path = ((BitmapImage)image.Source).UriSource.AbsolutePath;
【讨论】: