2

How do i get the duration of a .gif file in c#?

I would like to perform an action during the duration of time an animated gif file is playing, but for some reason i cannot find out how to get the length of time the gif will play.

piper2200s
  • 85
  • 6
  • 2
    Possible duplicate of [Getting the frame duration of an animated GIF?](https://stackoverflow.com/questions/3785031/getting-the-frame-duration-of-an-animated-gif) – Ipsit Gaur Nov 17 '17 at 04:34

1 Answers1

5

You can use this code:

public static class GifExtension
    {
        public static TimeSpan? GetGifDuration(this Image image, int fps = 60)
        {
            var minimumFrameDelay = (1000.0/fps);
            if (!image.RawFormat.Equals(ImageFormat.Gif)) return null;
            if (!ImageAnimator.CanAnimate(image)) return null;

            var frameDimension = new FrameDimension(image.FrameDimensionsList[0]);

            var frameCount = image.GetFrameCount(frameDimension);
            var totalDuration = 0;

            for (var f = 0; f < frameCount; f++)
            {
                var delayPropertyBytes = image.GetPropertyItem(20736).Value;
                var frameDelay = BitConverter.ToInt32(delayPropertyBytes, f * 4) * 10;
                // Minimum delay is 16 ms. It's 1/60 sec i.e. 60 fps
                totalDuration += (frameDelay < minimumFrameDelay ? (int) minimumFrameDelay : frameDelay);
            }

            return TimeSpan.FromMilliseconds(totalDuration);
        }
    }

EDIT: If you are sure, that all frames have the same duration – you can take only delay the first one.

Anton Gorbunov
  • 1,414
  • 3
  • 16
  • 24