ImageDown.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System;
  2. using System.IO;
  3. using System.Net;
  4. using System.Text.RegularExpressions;
  5. namespace Ant.Service.Utilities
  6. {
  7. /// <summary>
  8. /// 图片下载
  9. /// </summary>
  10. public class ImageDown
  11. {
  12. public ImageDown()
  13. { }
  14. #region 私有方法
  15. /// <summary>
  16. /// 获取图片标志
  17. /// </summary>
  18. private string[] GetImgTag(string htmlStr)
  19. {
  20. Regex regObj = new Regex("<img.+?>", RegexOptions.Compiled | RegexOptions.IgnoreCase);
  21. string[] strAry = new string[regObj.Matches(htmlStr).Count];
  22. int i = 0;
  23. foreach (Match matchItem in regObj.Matches(htmlStr))
  24. {
  25. strAry[i] = GetImgUrl(matchItem.Value);
  26. i++;
  27. }
  28. return strAry;
  29. }
  30. /// <summary>
  31. /// 获取图片URL地址
  32. /// </summary>
  33. private string GetImgUrl(string imgTagStr)
  34. {
  35. string str = "";
  36. Regex regObj = new Regex("http://.+.(?:jpg|gif|bmp|png)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
  37. foreach (Match matchItem in regObj.Matches(imgTagStr))
  38. {
  39. str = matchItem.Value;
  40. }
  41. return str;
  42. }
  43. #endregion
  44. /// <summary>
  45. /// 下载图片到本地
  46. /// </summary>
  47. /// <param name="strHTML">HTML</param>
  48. /// <param name="path">路径</param>
  49. /// <param name="nowyymm">年月</param>
  50. /// <param name="nowdd">日</param>
  51. public string SaveUrlPics(string strHTML, string path)
  52. {
  53. string nowym = DateTime.Now.ToString("yyyy-MM"); //当前年月
  54. string nowdd = DateTime.Now.ToString("dd"); //当天号数
  55. path = path + nowym + "/" + nowdd;
  56. if (!Directory.Exists(path)) Directory.CreateDirectory(path);
  57. string[] imgurlAry = GetImgTag(strHTML);
  58. try
  59. {
  60. for (int i = 0; i < imgurlAry.Length; i++)
  61. {
  62. string preStr = System.DateTime.Now.ToString() + "_";
  63. preStr = preStr.Replace("-", "");
  64. preStr = preStr.Replace(":", "");
  65. preStr = preStr.Replace(" ", "");
  66. WebClient wc = new WebClient();
  67. wc.DownloadFile(imgurlAry[i], path + "/" + preStr + imgurlAry[i].Substring(imgurlAry[i].LastIndexOf("/") + 1));
  68. }
  69. }
  70. catch (Exception ex)
  71. {
  72. return ex.Message;
  73. }
  74. return strHTML;
  75. }
  76. }
  77. }