Question

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);
Was it helpful?

Solution

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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top