大学IT网 - 最懂大学生的IT学习网站! QQ资料交流群:367606806
当前位置:大学IT网 > ASP.NET技巧 > ASP.NET保存远程图片到本地(代码)

ASP.NET保存远程图片到本地(代码)

关键词:ASP.NET远程图片本地代码  阅读(544) 赞(32)

[摘要]本文展示了ASP.NET保存远程图片到本地的核心函数,供大家参考学习!
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;
           }
       }
   }


相关评论