Search code examples
c#wpfanimated-gif

WPFAnimatedGif trows an System.OutOfRangeException


I'm trying to get a gif from a website animated in my WPF application by the following code. I'm using the WPFAnimatedGif library.

Image image = new Image();
var BtmImg = new BitmapImage();
string link = https://media.giphy.com/media/phJ6eMRFYI6CQ/giphy.gif;

BtmImg.BeginInit();
BtmImg.UriSource = new Uri(link);
BtmImg.EndInit();

ImageBehavior.SetAnimatedSource(image, BtmImg);
panel.Children.Add(image); //panel is a stackpanel defined in the xaml

This works fine if I'm going in the debug mode line by line through the code or if i add a litte sleep before the BtmImg.EndInit(); like System.Threading.Thread.Sleep(2000);

Otherwise i get an Exception: System.ArgumentOutOfRangeException: 'Specified argument was out of the range of valid values. Parameter name: index' This exception was originally thrown at this call stack: [External Code]

My guess is, that the gif is not fully downloaded as I'm trying to use it.

Has anybody an idea how to deal with it?


Solution

  • My guess is, that the gif is not fully downloaded as I'm trying to use it.

    That is exactly the problem. The best way is to set up a callback or event handler that is called after the download is completed, and then carry on with the rest of your setup. In this case the BitmapImage object comes with an event handler you can use.

    Try this:

        BtmImg.DownloadCompleted += (s, e) =>
        {
            ImageBehavior.SetAnimatedSource(image, BtmImg);
            panel.Children.Add(image); //panel is a stackpanel de
        };
    
        BtmImg.BeginInit();
        BtmImg.UriSource = new Uri(link);
        BtmImg.EndInit();