asp.net(C#)自动下载站外图片

翅膀的初衷

发表于2014-03-09 23:43:17

  一般情况下,大多数用户在转载网络上文章时,都会将文章内的图片下载到自己的服务器上!但是当图片数量很多的时候,这就变成了一个苦力活了!

  本文正是在该情况下,来实现程序自动下载站外地图!

  在上代码前,先讲下具体实现原理:

  第一步:通过正则表达式找出所有图片地址

  第二步:通过图片地址的域名与当前访问地址的域名进行比较判断是否外链图片

  第三步:使用System.Net下的WebClient下载图片到指定目录!

  第四步:替换链接地址

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
    protected string BatchDownloadPicture(string html,string savePath,string rootUrl)
    {
        List<Uri> result = new List<Uri>();
 
        System.Text.RegularExpressions.Regex objRegExp = new System.Text.RegularExpressions.Regex(@"(<img[^>]*?src\s*=\s*(['""]?))([^'""\s>]+)([^>]*>)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
 
        System.Text.RegularExpressions.MatchCollection mc = objRegExp.Matches(html);
 
        Uri uri;
 
        for (int i = 0; i < mc.Count; i++)
        {
            uri = new Uri(mc[i].Groups[3].Value);
            if (mc[i].Groups[3].Value.IndexOf("://") != -1 && !result.Contains(uri) && !Request.Url.Host.Equals(uri.Host, StringComparison.OrdinalIgnoreCase))
                result.Add(uri);
        }
 
        using (System.Net.WebClient wc = new System.Net.WebClient())
        {
            string extension;
            int index;
            string name;
            foreach (Uri node in result)
            {
                try
                {
                    index = node.AbsolutePath.LastIndexOf('.');
                    if (index > 0)
                    {
                        extension = node.AbsolutePath.Substring(index);
                    }
                    else
                    {
                        continue;
                    }
                    name = string.Concat(Guid.NewGuid().ToString("N"), extension);
 
                    wc.DownloadFile(node, string.Concat(savePath, name));
 
                    html = html.Replace(node.ToString(), string.Concat(rootUrl, name));
                }
                catch
                {
                    continue;
                }
            }
        }
 
        return html;
    }