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. | |
Please take a moment to rate this article (opens new browser window). Rate Article |
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 Morris is a 2004 and 2005 Microsoft MVP (Visual C#). During the day, you'll find this Sr. Software Engineer at Gartner in Maitland, FL coding away on the following tools: survey.gartner.com, Decision Tools For Vendor Selection, TCO Schools, and TVO. He is a co-developer of EggHeadCafe.com which is hosted by his web site development company RobbeMorris.com Inc. In his free time, Robbe likes to talk politics at the GOP Message Board. |