首页 .NET/Web ASP.NET保存远程图片到本地文件夹

ASP.NET保存远程图片到本地文件夹

作者:胡同里的砖头 围观群众:1232 更新于:2013-12-19

使用ASP.NET抓取远程图片保存到本地,是个不错的主意,这样图片的访问速度就快,以下是本站原创的保存远程图片到本地的函数,支持.bmp,.jpg,.jpeg,.gif,.png等格式的远程图片。

源代码如下:

导入命名空间

 

using System.Net;
using System.IO;
using System.Drawing.Imaging;

   /// <summary>
    /// 下载远程图片保存到本地
    /// </summary>
    /// <param name="savedir">本地保存路径</param>
    /// <param name="imgpath">远程图片文件</param>
    /// <returns></returns>
    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;
            }
        }
    }

//使用方法:

//如保存到本地的test目录:

Response.Write(this.downRemoteImg("test", "http://www.xueit.com/ads/top760.gif"));

 

  • 本文标题: ASP.NET保存远程图片到本地文件夹
  • 文章分类:【.NET/Web】
  • 非特殊说明,本文版权归【胡同里的砖头】个人博客 所有,转载请注明出处.
留言评论
站点声明:
1、本站【胡同里的砖头】个人博客,借鉴网上一些博客模板,取其各优点模块自行拼装开发,本博客开发纯属个人爱好。
2、所有笔记提供给广大用户交流使用,可转载,可复制,纯个人开发所遇问题锦集记录使用
Copyright © huzlblog.com All Rights Reserved. 备案号:苏ICP备2021056683号-8