Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split an animated gif in .net?

How do you split an animated gif into its component parts in .net?

Specifically I want to load them into Image(s) (System.Drawing.Image) in memory.

======================

Based on SLaks' answer i now have this

public static IEnumerable<Bitmap> GetImages(Stream stream)
{
    using (var gifImage = Image.FromStream(stream))
    {
        //gets the GUID
        var dimension = new FrameDimension(gifImage.FrameDimensionsList[0]);
        //total frames in the animation
        var frameCount = gifImage.GetFrameCount(dimension); 
        for (var index = 0; index < frameCount; index++)
        {
            //find the frame
            gifImage.SelectActiveFrame(dimension, index);
            //return a copy of it
            yield return (Bitmap) gifImage.Clone();
        }
    }
}
like image 722
Simon Avatar asked Nov 11 '09 02:11

Simon


People also ask

How do I extract a frame from a GIF in Photoshop?

Go to File > Export > Render Video…, then select a folder to save the images to be extracted, choose Photoshop Image Sequence, select an image format, BMP, JPEG, PNG or TIFF, then click on Render button and each frame should be exported to an image in the selected format saved to the folder you have selected above.


2 Answers

Use the SelectActiveFrame method to select the active frame of an Image instance holding an animated GIF. For example:

image.SelectActiveFrame(FrameDimension.Time, frameIndex);

To get the number of frames, call GetFrameCount(FrameDimension.Time)

If you just want to play the animation, you can put it into a PictureBox or use the ImageAnimator class.

like image 160
SLaks Avatar answered Oct 03 '22 01:10

SLaks


// Parses individual Bitmap frames from a multi-frame Bitmap into an array of Bitmaps

private Bitmap[] ParseFrames(Bitmap Animation)
{
    // Get the number of animation frames to copy into a Bitmap array

    int Length = Animation.GetFrameCount(FrameDimension.Time);

    // Allocate a Bitmap array to hold individual frames from the animation

    Bitmap[] Frames = new Bitmap[Length];

    // Copy the animation Bitmap frames into the Bitmap array

    for (int Index = 0; Index < Length; Index++)
    {
        // Set the current frame within the animation to be copied into the Bitmap array element

        Animation.SelectActiveFrame(FrameDimension.Time, Index);

        // Create a new Bitmap element within the Bitmap array in which to copy the next frame

        Frames[Index] = new Bitmap(Animation.Size.Width, Animation.Size.Height);

        // Copy the current animation frame into the new Bitmap array element

        Graphics.FromImage(Frames[Index]).DrawImage(Animation, new Point(0, 0));
    }

    // Return the array of Bitmap frames

    return Frames;
}
like image 44
Neoheurist Avatar answered Oct 03 '22 03:10

Neoheurist