Click here to Skip to main content
Click here to Skip to main content

Tagged as

Go to top

C# Get Frames from a GIF

, 2 Aug 2014
Rate this:
Please Sign up or sign in to vote.
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 InformationAs you know, GIFs contain various images (frames) that are displayed one by one after a certa
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)

{

    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;

}



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)

Share

About the Author

Apex95
Student
Romania Romania
No Biography provided

Comments and Discussions

 
GeneralMy vote of 5 PinmemberCarsten V2.03-Aug-14 7:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140916.1 | Last Updated 2 Aug 2014
Article Copyright 2014 by Apex95
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid