验证在运行时从URI加载的WPF位图图像

时间:2012-04-19 16:13:00

标签: c# wpf xaml code-behind bitmapimage

我正在尝试从URI加载运行时的BitmapImage。我在我的XAML用户控件中使用默认图像,我想通过数据绑定替换它。这很有效。

我遇到的问题是在无效文件用于替换图像的情况下(可能是错误的URI,或者URI指定的是非图像文件)。发生这种情况时,我希望能够检查BitmapImage对象以查看它是否正确加载。如果没有,我想坚持使用默认图像。

这是XAML:

<UserControl x:Class="MyUserControl">
    <Grid>
        <Image
            x:Name="myIcon"
            Source="Images/default.png" />
    </Grid>
</UserControl>

相关的代码隐藏:

public static readonly DependencyProperty IconPathProperty =
    DependencyProperty.Register(
        "IconPath",
        typeof(string),
        typeof(MyUserControl),
        new PropertyMetadata(null, new PropertyChangedCallback(OnIconPathChanged)));

public string IconPath
{
    get { return (string)GetValue(IconPathProperty); }
    set { SetValue(IconPathProperty, value); }
}

private static void OnIconPathChanged(
    object sender,
    DependencyPropertyChangedEventArgs e)
{
    if (sender != null)
    {
        // Pass call through to the user control.
        MyUserControl control = sender as MyUserControl;
        if (control != null)
        {
            control.UpdateIcon();
        }
    }
}

public void UpdateIcon()
{
    BitmapImage replacementImage = new BitmapImage();

    replacementImage.BeginInit();
    replacementImage.CacheOption = BitmapCacheOption.OnLoad;

    // Setting the URI does not throw an exception if the URI is
    // invalid or if the file at the target URI is not an image.
    // The BitmapImage class does not seem to provide a mechanism
    // for determining if it contains valid data.
    replacementImage.UriSource = new Uri(IconPath, UriKind.RelativeOrAbsolute);

    replacementImage.EndInit();

    // I tried this null check, but it doesn't really work.  The replacementImage
    // object can have a non-null UriSource and still contain no actual image.
    if (replacementImage.UriSource != null)
    {
        myIcon.Source = replacementImage;
    }
}

以下是我如何在另一个XAML文件中创建此用户控件的实例:

<!--
  My problem:  What if example.png exists but is not a valid image file (or fails to load)?
-->
<MyUserControl IconPath="C:\\example.png" />

也许有人可以建议一种不同/更好的方法来在运行时加载图像。感谢。

4 个答案:

答案 0 :(得分:1)

好吧,BitmapImage类有两个事件,当下载或解码失败时会引发这两个事件。

yourBitmapImage.DownloadFailed += delegate { /* fall to your def image */ }
yourBitmapImage.DecodeFailed += delegate { /* fall to your def img */ }

另外,如果您正在尝试实施后备占位符:http://www.markermetro.com/2011/06/technical/mvvm-placeholder-images-for-failed-image-load-on-windows-phone-7-with-caliburn-micro/似乎很不错。

答案 1 :(得分:0)

您可以尝试此检查

        if (bitmapImage.UriSource==null || bitmapImage.UriSource.ToString()).Equals(""))
        {
            Console.WriteLine("path null");
        }
        else
        {
            bitmapImage.EndInit();
        }

答案 2 :(得分:0)

很粗糙,但我发现无效的BitmapImage的宽度和高度为0。

id

答案 3 :(得分:-2)

这已经得到了解答。请查看thisthis。我认为他们都有点回答你的问题,但我更喜欢前一种方法,因为它甚至会检查远程资源的contentType。

您还可以查看此post

更新

如果是本地文件,只需使用Uri或路径创建Image对象即可检查。如果成功,则表示图像是有效图像:

try
{
    Image image = Image.FromFile(uri);
    image.Dispose();
}
catch (Exception ex)
{
    //Incorrect uri or filetype.
}
相关问题