简体   繁体   English

如何在C#中获取.gif文件的持续时间?

[英]How do you get the duration of a .gif file in c#?

How do i get the duration of a .gif file in c#? 如何在C#中获取.gif文件的持续时间?

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. 我想在播放动画gif文件的过程中执行操作,但是由于某些原因,我无法找到如何获取gif播放时间的长度。

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. 编辑:如果您确定,所有帧都具有相同的持续时间–您只能延迟第一个帧。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM