C# Programming > Drawing GDI+

C# Displaying Animated GIF


Animated GIF

A C# animated GIF can be easy to manage. Displaying animated GIFs in C# has become incredibly simple starting with the .NET Framework 2.0. You have to options to display an animated GIF automatically handled by the .NET Framework or manually to fine-control the animation of the image.

The Automatic Way - C# PictureBox

c# animated gif

The first way to display an animated GIF in C# is using the PictureBox control. By settings the PictureBox control's Image property to an animated GIF, the PictureBox will automatically display the animation:

pictureBox1.Image = Image.FromFile("C:/Images/animated.gif");

C# makes things so simple right? The downside to this method is that you as the programmer have no control over the FPS (frames per second) of the animation or in the way in which it loops.

If you want to handle those things yourself then we need some C# code to manually access the frames in the animation.

The Manual Way - Extract Frames

There are two things we need to handle animated GIF with purely C# code. Both will require the System.Drawing.Imaging namespace.

First we need a count of the total number of frames in the animated GIF. Use a combination of the Image and FrameDimension classes:

Image gifImage = Image.FromFile(path);
FrameDimension dimension = new FrameDimension(gifImage.FrameDimensionsList[0]);
int frameCount = gifImage.GetFrameCount(dimension);

Notice that you only need the first GUID from the FrameDimensionList.

The second part is to actually access the desired frame. Use the following line of code:

gifImage.SelectActiveFrame(dimension, index);

SelectActiveFrame will return an integer that you do not necessarily need. The important part is it will transform the image into only the selected frame.

Animated GIF C# Class

It would be possibly to create a C# class that would handle frame extraction from C# animated GIFs automatically for us. And that is exactly what we are going to do...


Continue to Page 2 - C# Animated GIF Class

Back to C# Article List