Download animated GIF

I use below to capture an animated gif from the Internet. However, saving this to disk, I lose the frames in the gif, and it no longer animates. Not sure if the problem is in the method below, or when I save it, but any feedback on why below will not be evaluated. This method works - just without creating the desired 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);
+5
source share
1 answer

You should not create Imagefrom a stream ( it will save only the first frame ). Instead, you should write the content Streamdirectly to disk, using, for example, a method Stream.CopyToto copy the contents to a FileStreamthat you created for the target file.

using (Stream stream = httpWebReponse.GetResponseStream())
using (FileStream fs = File.Create(path))
{
    stream.CopyTo(fs);
}
+7
source

All Articles