//调用示例 downRemoteImg("Images", "http://common.cnblogs.com/images/qdigg.gif"); public string downRemoteImg(string savedir, string imgpath) { if (string.IsNullOrEmpty(imgpath)) { return string.Empty; } else { string imgName = string.Empty; string imgExt = string.Empty; string saveFilePath = string.Empty; imgName = imgpath.Substring(imgpath.LastIndexOf("/"), imgpath.Length - imgpath.LastIndexOf("/")); imgExt = imgpath.Substring(imgpath.LastIndexOf("."), imgpath.Length - imgpath.LastIndexOf(".")); saveFilePath = Server.MapPath(savedir); if (!Directory.Exists(saveFilePath)) Directory.CreateDirectory(saveFilePath); try { WebRequest wreq = WebRequest.Create(imgpath); wreq.Timeout = 10000; HttpWebResponse wresp = (HttpWebResponse)wreq.GetResponse(); Stream s = wresp.GetResponseStream(); System.Drawing.Image img; img = System.Drawing.Image.FromStream(s); switch (imgExt.ToLower()) { case ".gif": img.Save(saveFilePath + imgName, ImageFormat.Gif); break; case ".jpg": case ".jpeg": img.Save(saveFilePath + imgName, ImageFormat.Jpeg); break; case ".png": img.Save(saveFilePath + imgName, ImageFormat.Png); break; case ".icon": img.Save(saveFilePath + imgName, ImageFormat.Icon); break; case ".bmp": img.Save(saveFilePath + imgName, ImageFormat.Bmp); break; } img.Dispose(); s.Dispose(); return savedir + imgName; } catch { return imgpath; } } }
Demo如上,你更改一下图片存放路径跟图片地址就可以了
这样保存的gif只有一帧,我想保存完整的gif
@ninglee515: 改成这样:
using (WebClient wc = new WebClient()) { wc.DownloadFile("http://space.cnblogs.com/Emoticons/others/drink.gif", Server.MapPath("Images") + "\\test.gif"); }
@artwl: 恩谢谢。还想问个问题啊。就是我保存网络图片是直接用webclient呢还是除了gif用webclient其他格式的用System.Drawing.Image。他们的效率怎么样!