Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / All-Topics

C# Get Frames from a GIF

5.00/5 (2 votes)
2 Aug 2014CPOL1 min read 19.2K  
This is a simple method to extract a certain frame (or all of them) from a GIF, using C#.
This is a simple method to extract a certain frame (or all of them) from a GIF, using C#. As always, .NET provides all the functions we need, so it shouldn't take more than 12 lines of code.


Basic Information



As you know, GIFs contain various images (frames) that are displayed one by one after a certain time interval (unlike TIFFs, that display all the frames simultaneously in one picture). However we'll be working with the GIF format (whose frames are entirely based on the time dimension).


In order to get the number of frames we'll use GetFrameCount(FrameDimension.Time), which returns an int. Note that it requires an argument that specifies the dimension.

Next, we have to iterate through each frame and then select it using the same dimension and an index (SelectActiveFrame(FrameDimension.Time, indexOfCurrentFrame)).

Important: This method modifies the original image, so we'll need to call Clone() on this object and cast it as an Image before saving it (otherwise we'd just save the GIF - not the current frame).


Example



This small function extracts & returns an array of frames (Image), from a given picture.

* Recommend executing this in a worker thread, especially when GIFs have many frames.

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



It can be called like this:
Image[] frames = getFrames(Image.FromFile("random.gif"));



License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)