HOWTO: create an animated GIF using .Net (C#)
.Net (at least 1.1, they might incorporate it in 2.0) does not give you possibilities to create animated GIFs through GDI+. But there are ways to make them! This solution is one I used myself, and I'm very pleased!
stringCollection = a_StringCollection_containing_images;
Response.ContentType = "Image/gif";
memoryStream = new MemoryStream();
buf2 = new Byte;
buf3 = new Byte;
buf2 = 33; //extension introducer
buf2 = 255; //application extension
buf2 = 11; //size of block
buf2 = 78; //N
buf2 = 69; //E
buf2 = 84; //T
buf2 = 83; //S
buf2 = 67; //C
buf2 = 65; //A
buf2 = 80; //P
buf2 = 69; //E
buf2 = 50; //2
buf2 = 46; //.
buf2 = 48; //0
buf2 = 3; //Size of block
buf2 = 1; //
buf2 = 0; //
buf2 = 0; //
buf2 = 0; //Block terminator
buf3 = 33; //Extension introducer
buf3 = 249; //Graphic control extension
buf3 = 4; //Size of block
buf3 = 9; //Flags: reserved, disposal method, user input, transparent color
buf3 = 10; //Delay time low byte
buf3 = 3; //Delay time high byte
buf3 = 255; //Transparent color index
buf3 = 0; //Block terminator
binaryWriter = new BinaryWriter(Response.OutputStream);
for (int picCount = 0; picCount < stringCollection.Count; picCount++)
image = Bitmap.FromFile(stringCollection[picCount]);
buf1 = memoryStream.ToArray();
if (picCount == 0)
//only write these the first time....
binaryWriter.Write(buf1, 0, 781); //Header & global color table
binaryWriter.Write(buf2, 0, 19); //Application extension
binaryWriter.Write(buf3, 0, 8); //Graphic extension
binaryWriter.Write(buf1, 789, buf1.Length - 790); //Image data
if (picCount == stringCollection.Count - 1)
//only write this one the last time....
binaryWriter.Write(";"); //Image terminator
To illustratie te poor quality I'm talking about, I've added an animated gif created dynamically using the code above, based on a directory containing some source images. Look at the 'raster' in the darker images... (the source images were solid filled 200 x 200 GIF's, created using Paint.Net, where they look fine)
Damn Paint.Net! I make a test-image: looks great. I save it as a GIF: still looks great. Use it in my anigif-code: no more greatness. I reopen the file in Paint.Net: then it's fubar! Creating the testfiles in oldskool Paint solves this (because you only have GIF-supported colors in your toolbar)...
When you are converting a file to a GIF, old Paint warns you because you might be losing color information, Paint.Net does not. Paint reloads the file the way you saved it so you see what remains. Paint.Net does not. These are two wannahaves on Paint.Net for me!
Thanks to Dennis for pointing out a small glitch in my type-work.
It should have been 'picCount == stringCollection.Count - 1'.