5

I'm using the below to grab an animated gif off the web. However, upon saving this to disk, I lose the frames in the gif, and it no longer animates. Not sure whether the problem is in the below method, or whether it's when I'm saving it, but any feedback on why the below wouldn't work appreciated. The method is working - just not creating a proper animated gif file.

public Image getImage(String url)
{
    HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
    HttpWebResponse httpWebReponse = (HttpWebResponse)httpWebRequest.GetResponse();
    Stream stream = httpWebReponse.GetResponseStream();
    return Image.FromStream(stream, true, true);
}

Image im = getImage(url)
im.Save(pth,ImageFormat.Gif);
John Saunders
  • 160,644
  • 26
  • 247
  • 397
Squiggs.
  • 4,299
  • 6
  • 49
  • 89
  • 1
    Can you use the WebImage class? Alternatively, don't even treat it as an Image, which would process it, but rather just as a stream of bytes and save that to a file with a .gif extension; if what they uploaded was an animated gif, it would be save it correctly. – Rob G Mar 29 '13 at 23:14
  • possible duplicate of [C# gif Image to MemoryStream and back (lose animation)](http://stackoverflow.com/questions/8763630/c-sharp-gif-image-to-memorystream-and-back-lose-animation) – Blachshma Mar 29 '13 at 23:15

1 Answers1

8

You should not create an Image from the stream (it will only store the first frame). Instead, you should write the contents of the Stream directly to disk using, for example, the Stream.CopyTo method to copy the content to a FileStream you created for the destination file.

using (Stream stream = httpWebReponse.GetResponseStream())
using (FileStream fs = File.Create(path))
{
    stream.CopyTo(fs);
}
Community
  • 1
  • 1
Daniel A.A. Pelsmaeker
  • 47,471
  • 20
  • 111
  • 157