C#图片下载源代码

using System;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;

namespace DotNet.Utilities
{
///
/// 图片下载
///
public class ImageDown
{
public ImageDown()
{ }

    #region 私有方法
    /// <summary>
    /// 获取图片标志
    /// </summary>
    private string[] GetImgTag(string htmlStr)
    {
        Regex regObj = new Regex("<img.+?>", RegexOptions.Compiled | RegexOptions.IgnoreCase);
        string[] strAry = new string[regObj.Matches(htmlStr).Count];
        int i = 0;
        foreach (Match matchItem in regObj.Matches(htmlStr))
        {
            strAry[i] = GetImgUrl(matchItem.Value);
            i++;
        }
        return strAry;
    }

    /// <summary>
    /// 获取图片URL地址
    /// </summary>
    private string GetImgUrl(string imgTagStr)
    {
        string str = "";
        Regex regObj = new Regex("http://.+.(?:jpg|gif|bmp|png)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
        foreach (Match matchItem in regObj.Matches(imgTagStr))
        {
            str = matchItem.Value;
        }
        return str;
    }
    #endregion

    /// <summary>
    /// 下载图片到本地
    /// </summary>
    /// <param name="strHTML">HTML</param>
    /// <param name="path">路径</param>
    /// <param name="nowyymm">年月</param>
    /// <param name="nowdd">日</param>
    public string SaveUrlPics(string strHTML, string path)
    {
        string nowym = DateTime.Now.ToString("yyyy-MM");  //当前年月
        string nowdd = DateTime.Now.ToString("dd");       //当天号数
        path = path + nowym + "/" + nowdd;
        if (!Directory.Exists(path)) Directory.CreateDirectory(path);

        string[] imgurlAry = GetImgTag(strHTML);
        try
        {
            for (int i = 0; i < imgurlAry.Length; i++)
            {
                string preStr = System.DateTime.Now.ToString() + "_";
                preStr = preStr.Replace("-", "");
                preStr = preStr.Replace(":", "");
                preStr = preStr.Replace(" ", "");
                WebClient wc = new WebClient();
                wc.DownloadFile(imgurlAry[i], path + "/" + preStr + imgurlAry[i].Substring(imgurlAry[i].LastIndexOf("/") + 1));
            }
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
        return strHTML;
    }
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值