private static BitmapDecoder GetDecoder(BitmapSource image, out GifFile gifFile) { gifFile = (GifFile)null; BitmapDecoder decoder = (BitmapDecoder)null; Stream stream = (Stream)null; Uri result = (Uri)null; BitmapCreateOptions createOptions = BitmapCreateOptions.None; if (image is BitmapImage bitmapImage) { createOptions = bitmapImage.CreateOptions; if (bitmapImage.StreamSource != null) { stream = bitmapImage.StreamSource; } else if (bitmapImage.UriSource != (Uri)null) { result = bitmapImage.UriSource; if (bitmapImage.BaseUri != (Uri)null && !result.IsAbsoluteUri) { result = new Uri(bitmapImage.BaseUri, result); } } } else if (image is BitmapFrame bitmapFrame) { decoder = bitmapFrame.Decoder; Uri.TryCreate(bitmapFrame.BaseUri, bitmapFrame.ToString((IFormatProvider)CultureInfo.InvariantCulture), out result); } if (decoder == null) { if (stream != null) { stream.Position = 0L; decoder = BitmapDecoder.Create(stream, createOptions, BitmapCacheOption.OnLoad); } else if (result != (Uri)null && result.IsAbsoluteUri) { decoder = BitmapDecoder.Create(result, createOptions, BitmapCacheOption.OnLoad); } } if (decoder is GifBitmapDecoder && !ImageBehavior.CanReadNativeMetadata(decoder)) { if (stream != null) { stream.Position = 0L; gifFile = GifFile.ReadGifFile(stream, true); } else { if (!(result != (Uri)null)) { throw new InvalidOperationException("Can't get URI or Stream from the source. AnimatedSource should be either a BitmapImage, or a BitmapFrame constructed from a URI."); } gifFile = ImageBehavior.DecodeGifFile(result); } } if (decoder == null) { throw new InvalidOperationException("Can't get a decoder from the source. AnimatedSource should be either a BitmapImage or a BitmapFrame."); } return(decoder); }