Search code examples
c#winformsgifpicturebox

C# PictureBox with animated GIF skips Frames


i have the Problem that my animated gif i used as IMAGE Value in my PictureBox Control is shown slower than showing in Explorer.

I'm using C# Winforms.

Problem here should be that some frames are skipped in execution.

Can someone confirm this issue and maybe have a solution for that?

My Picture Box is for Preloading and works fully in Background Thread.

Is it maybe possible to read the Frames one by one from the gif and animate it selfmade to picturebox?

Thanks!


Solution

  • Use this code. Since 25 frames per second is displayed, I set the timer to 40, which means one frame every 40 milliseconds. (1000ms / 25 frames = 40ms)

    step 1. This method shows how to use

    static Image[] images;
    int frameCount = 0;
    private void Btn_Click(object sender, EventArgs e)
    {  
        //get gif image
        object ezgif_com_video_to_gif = Resources.ResourceManager.GetObject("ezgif_com_video_to_gif");
        images = getFrames((Image)ezgif_com_video_to_gif);//convert to frames array
    
        //show frames
        System.Timers.Timer timer = new System.Timers.Timer();
        timer.Interval = 40;
        timer.Elapsed += Timer_Elapsed;
        timer.Start();
    }
    

    step 2. add timer tick

    private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        pictureBox1.Image = images[frameCount];
        frameCount++;
        if (frameCount > images.Length - 1)
            frameCount = 0;
    }
    

    step 3. convert gif to frames

    Image[] getFrames(Image originalImg)
    {
        int numberOfFrames = originalImg.GetFrameCount(FrameDimension.Time);
        Image[] frames = new Image[numberOfFrames];
    
        for (int i = 0; i < numberOfFrames; i++)
        {
            originalImg.SelectActiveFrame(FrameDimension.Time, i);
            frames[i] = ((Image)originalImg.Clone());
        }
    
        return frames;
    }