Validating a WPF Bitmap Image Loaded from a URI in Runtime

I am trying to load BitmapImage at runtime from a URI. I use the default image in my XAML user control, which I would like to replace with data binding. It works.

The problem I ran into is when an invalid file is used for the replacement image (maybe this is an invalid URI, or maybe the URI indicates a file without an image). When this happens, I want to check the BitmapImage object to make sure that it was loaded correctly. If not, I want to stick with the default image used.

Here's the XAML:

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

And the corresponding codebehind:

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

And here is how I can create an instance of this user control in another XAML file:

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

, , - / . .

+3
4

, 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

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

, , BitmapImage 0.

    BitmapImage image;
    if(image.Width > 0 && image.Height > 0) 
    {  
        //valid image 
    }     
0

This has already been answered. Check out this and this . I think both of them answer your question somewhat, but I would prefer the previous approach, since it even checks the contentType of the remote resource.

You can also view this post .

Update:

In the case of local files, this can be verified simply by creating an Image object using a Uri or path. If successful, this means that the image is a valid image:

try
{
    Image image = Image.FromFile(uri);
    image.Dispose();
}
catch (Exception ex)
{
    //Incorrect uri or filetype.
}
-2
source

All Articles