你现在的位置:首页>>WEB编程>>ASP.NET >>.NET如何获得远程图片(经测试能正常运行)

.NET如何获得远程图片(经测试能正常运行)

更新时间:2010-6-9 01:38:24   浏览次数:288
关键词:保存远程图片到本地         

如何获得远程图片,这种方法对于复制网上资料有很好的帮助,不需要一个一个图片的保存。一下子把所有图片全下来了。

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动画,那获得后,只有第一帧。

随机推荐文章
CopyRight © 2008-2010  糊涂蛋技术网   苏ICP备05013073号
站长:xlxcn QQ:54960248  三郎 QQ:120554323   E-mail:xlxcn#126.com