如何获得远程图片,这种方法对于复制网上资料有很好的帮助,不需要一个一个图片的保存。一下子把所有图片全下来了。
public downRemoteImgs()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
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("."));
GetupFileName gimgname=new GetupFileName();
string newImgName = gimgname.getfilename() + imgExt;
saveFilePath = System.Web.HttpContext.Current.Server.MapPath(savedir);
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 + newImgName, ImageFormat.Gif);
break;
case ".jpg":
case ".jpeg":
img.Save(saveFilePath + newImgName, ImageFormat.Jpeg);
break;
case ".png":
img.Save(saveFilePath + newImgName, ImageFormat.Png);
break;
case ".icon":
img.Save(saveFilePath + newImgName, ImageFormat.Icon);
break;
case ".bmp":
img.Save(saveFilePath + newImgName, ImageFormat.Bmp);
break;
}
img.Dispose();
s.Dispose();
return savedir + newImgName;
}
catch
{
return string.Empty;
}
}
}
调用方法:
string newDownloadImg = downloadImg.downRemoteImg("uploadfile/", Rimgs[ri].ToString());
当newDownloadImg 为null时,表示没有获得成功。
但有一点是,如果是GIF动画,那获得后,只有第一帧。