Reading Metadata property of GifBitmapDecoder…why

2019-03-01 06:19发布

问题:

How can I read the delay, left and top offset data for each frame of a gif? I've gotten this far.

  1. Load the Gif

    var myGif = new GifBitmapDecoder(uri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);

  2. Get a frame

    var frame = myGif.Frames[i];

  3. From MSDN: Native Image Format Metadata Queries read (ushort)Metadata.GetQuery("/grctlext/Delay"), (ushort)Metadata.GetQuery("/imgdesc/Left"), (ushort)Metadata.GetQuery("/imgdesc/Top")

But two things don't work. First the Metadata property of both the gif and the frame are always null, even if I try different animated gif files. Second, the Metadata property of the frame doesn't seem to have a GetQuery method.

How do I run these queries, what did I miss?

Edit:

Here is sample code that gives me null metadata. Using a fresh install of VS2010 Premium, on a fresh WPF application. The image file is the one in the comments.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            var uri = new Uri(@"c:\b-414328-animated_gif_.gif");
            var myGif = new GifBitmapDecoder(uri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
            var frame = myGif.Frames[0];

            Title = "";
            Title += "Global Metadata is null: " + (myGif.Metadata == null).ToString();
            Title += "; Frame Metadata is null: " + (frame.Metadata == null).ToString();

            // Crash due to null metadata
            //var frameData = (BitmapMetadata)frame.Metadata;
            //var rate = (ushort)frameData.GetQuery("/grctlext/Delay");

        }
    }
}

回答1:

First, you need to Freeze the Frame you want to obtain the metadata from:

var frame = myGif.Frames[0];
frame.Freeze();

Second, the frame.Metadata returns an ImageMetadata which does not have a GetQuery method, but in fact the object returned is of type BitmapMetadata which has a GetQuery method, so you just need to cast frame.Metadata to BitmapMetadata as you do in the last commented lines of your code.