Strip Images From Animated Gif

By Robbe D. Morris

Printer Friendly Version

Robbe Morris
Robbe & Melisa Morris
  Download C# Source Code
Ever run across an animated gif file that you wanted to pull apart and manipulate?  The following code snippet will demonstrate how to use GDI+ in .NET to extract each frame in the animated gif and write it to disk.  Essentially, you get the frame count and then iterate through the frames.  When the .SelectActiveFrame method is used on the image, it sets the current image in the specified frame as a reference point for the image.
In order to make sure that the image quality remains as good with each copied image frame, I opted to use the quantization technique from the fantastic article Optimizing Color Quantization for ASP.NET Images by Morgan Skinner.  The source code for Morgan's technique is also included my code sample.


C# Source Code
using System;
using System.Drawing;
using System.Drawing.Imaging;

namespace StripAnimation
{
 
  class Class1
  {
		
     [STAThread]
     static void Main(string[] args)
     {
        StripAnimation.Stripper oStripper = new StripAnimation.Stripper();
        oStripper.Strip("sample.gif","","frame"); 
     }
  }
 
  public class Stripper
  {

    public void Strip(string FileName,string OutputFolder,string OutputBaseName)
    {
			 
      ImageManipulation.OctreeQuantizer quantizer = null;

      string OutputFileName = OutputFolder + OutputBaseName;
			
      Image MasterImage = Image.FromFile(FileName);
		 
      FrameDimension oDimension = new FrameDimension(MasterImage.FrameDimensionsList[0]);

      int FrameCount = MasterImage.GetFrameCount(oDimension);

      for(int i=0;i<FrameCount;i++)
      {

        MasterImage.SelectActiveFrame(oDimension,i); 

        quantizer = new ImageManipulation.OctreeQuantizer(255,8);
			  
        using ( Bitmap quantized = quantizer.Quantize(MasterImage) )
        {
          quantized.Save(OutputFileName + i.ToString() + ".gif",ImageFormat.Gif);
        }

      }
  
      MasterImage.Dispose(); 
			
   }
 
  }
}

Robbe has been a Microsoft MVP in C# since 2004.  He is also the co-founder of NullSkull.com which provides .NET articles, book reviews, software reviews, and software download and purchase advice.