C# gif Image to MemoryStream and back (lose animation)

When you load your image from a Stream, the .NET framework detects that the GIF is animated. Since it knows that it will be unable to reencode an animated GIF, it tries to store the original encoding of the GIF. But this happens after it has read the stream and decoded the GIF. So when it tries to rewind the stream this fails and it ends up not storing the original.

When you call Save() it first checks whether it has the original encoding stored. But since that operation failed, it attempts to reencode the GIF. Since .NET does not have an encoder for animated GIFs, it only encodes the first frame.

If you use a FileStream instead it works, since a FileStream is seekable.

You can make your code work by loading the response into a MemoryStream first:

// ...
Stream stream = httpWebReponse.GetResponseStream();

MemoryStream memoryStream = new MemoryStream();
stream.CopyTo(memoryStream);
memoryStream.Position = 0;
stream = memoryStream;

Image img = Image.FromStream(stream);
// ...

If you want to see what happens, enable .NET reference source debugging and note what happens in Image.EnsureSave(). You will also note that the Image-implementation already copies the Stream into a MemoryStream, so that they could fix the problem by using that instead of the original Stream.


GDI+ does not contain any animated GIF encoder (just a decoder). So your img.Save will drop the animation. But you could try this: http://www.codeproject.com/KB/GDI-plus/NGif.aspx