文本编辑器加保存远程图片到本地目录功能

代码中使用的是FreeTextBox控件,用其它的控件也可以,通过正规表达式分析HTML代码中含有<img...>这样的标记,然后循环下载图片并替换掉HTML代码中的内容,改为本地图片的路径。

        string pageBody = this.FreeTextBox1.Text;
        if (this.CheckBox_SavePic.Checked)
        {
            MatchCollection matchs = Regex.Matches(pageBody, "(?<=<img.+?src\\s*?=\\s*?\"?)([^\\s\"]+?)(?=[\\s\"])", RegexOptions.Singleline);
            for (int i = 0; i < matchs.Count; i++)
            {

                string picUrl = matchs[i].Groups[1].Value;

                if (!picUrl.ToLower().EndsWith("jpg") && !picUrl.ToLower().EndsWith("jpeg") && !picUrl.ToLower().EndsWith("gif") && !picUrl.ToLower().EndsWith("bmp") && !picUrl.ToLower().EndsWith("png")) continue;

                string newPicUrl = downloadPic(picUrl.Trim());
                pageBody = pageBody.Replace(picUrl, newPicUrl);
            }
        }

pageBody就是最后要保存的HTML内容了

下载图片

    private string downloadPic(string picUrl)
    {
        DateTime now = DateTime.Now;
        string picDirName = string.Format("{0}-{1}-{2}", now.Year, now.Month, now.Day);
        
        string savePath = Server.MapPath("./upLoad/NewsImg/") + picDirName;
        if (!System.IO.Directory.Exists(savePath)) //判断目录是否存在
        {
            System.IO.Directory.CreateDirectory(savePath);
        }
        string picExt = System.IO.Path.GetExtension(picUrl).ToLower();
        string saveName = DateTime.Now.ToString("yyyyMMddHHmmssffff");//根据日期生成随机的文件名
        System.Net.WebClient client = new System.Net.WebClient();
        client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
        string newName = savePath + "\\" + saveName + picExt;
        try
        {
            client.DownloadFile(picUrl, newName); //用WebClient下载图片到本地
        }
        catch
        {
            
        }
        return newName.Replace(Server.MapPath("."), ".");//返回内容时替换绝对路径
    }

注:理论上用WebClient直接下载图片到本地目录,其实是有一定风险的,因为不能保证别人有没有在图片上做手脚,但采集来的人是自己,相对来说是安全的。

代码如果要改进可以用流方式把图片读到内存中,然后重新Drawing到本地目录中,这个代码只是为了演式用的,以后有空会把改进的代码放上来。

posted @ 2012-10-07 18:19  寂静之秋  阅读(507)  评论(0编辑  收藏  举报
哈尔滨八零网