程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> .NET實例教程 >> ASP.NET保存遠程圖片到本地的函數

ASP.NET保存遠程圖片到本地的函數

編輯:.NET實例教程

使用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;
                }

    &nb
sp;           img.Dispose();
                s.Dispose();

                return savedir + imgName;
            }
            catch
            {
                return imgpath;
            }
        }
    }

使用方法:

如保存到本地的test目錄:

Response.Write(this.downRemoteImg("test", "/School/UploadFiles_7810/201104/20110421222547805.gif"));

作者:dodo 原文:http://www.xueit.com/html/2009-08/21_4234_00.Html


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved