通过 WebBrowser 获取网页截图(第二种)

本文介绍了一种通过WebBrowser控件获取网页截图的稳定方法。相比使用navigate,该方法利用HTML文件流作为参数,在确保截取完整图片的同时,避免了可能出现的截取不全问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  这边提供第二种方式,前一种是用了webbrowser的线程安全,然后开启单线程等到webbrowser加载完成才drawimage来截图,比较稳定,这个方法在用openfiledialog打开文件后通过html的流来作为入参来截取比较稳定,如果用navigate会出现一些截取图片不完整的现象。下面上调用的函数定义:

 public class HtmlThumbnail
    {
        private static Bitmap m_Bitmap;
        private static int m_BrowserWidth = 580;
        private static int m_BrowserHeight = 10;
        private static string showHtml = "";

        public HtmlThumbnail(string HtmlContent, int BrowserWidth, int BrowserHeight)
        {
            showHtml = HtmlContent;
            m_BrowserHeight = BrowserHeight;
            m_BrowserWidth = BrowserWidth;
        }

        public static Bitmap GetWebSiteThumbnail(string HtmlContent, int BrowserWidth, int BrowserHeight)
        {
            HtmlThumbnail thumbnailGenerator = new HtmlThumbnail(HtmlContent, BrowserWidth, BrowserHeight);
            return thumbnailGenerator.GenerateWebSiteThumbnailImage();
        }

        public Bitmap GenerateWebSiteThumbnailImage()
        {
            Thread m_thread = new Thread(new ThreadStart(_GenerateWebSiteThumbnailImage));
            m_thread.SetApartmentState(ApartmentState.STA);
            m_thread.Start();
            m_thread.Join();
            return m_Bitmap;
        }
        private void _GenerateWebSiteThumbnailImage()
        {
            System.Windows.Forms.WebBrowser m_WebBrowser = new System.Windows.Forms.WebBrowser();
            m_WebBrowser.ScrollBarsEnabled = false;
            m_WebBrowser.Navigate("about:blank");
            m_WebBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);
            while (m_WebBrowser.ReadyState != WebBrowserReadyState.Interactive)
                Application.DoEvents();
            m_WebBrowser.Dispose();
        }
        private void WebBrowser_DocumentCompleted(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
        {
            WebBrowser m_WebBrowser = (WebBrowser)sender;
          <span style="color:#ff0000;">  m_WebBrowser.Document.Write(showHtml);</span>
            <span style="color:#339999;">//m_WebBrowser.Navigate(showHtml);</span>
            /*
            m_WebBrowser.ClientSize = new Size(m_BrowserWidth, m_BrowserHeight);
            m_WebBrowser.ScrollBarsEnabled = false;
            m_Bitmap = new Bitmap(m_WebBrowser.Bounds.Width, m_WebBrowser.Bounds.Height);
            m_WebBrowser.BringToFront();
            m_WebBrowser.DrawToBitmap(m_Bitmap, m_WebBrowser.Bounds);
            */
            m_WebBrowser.ClientSize = new Size(m_WebBrowser.Document.Body.ScrollRectangle.Width, m_WebBrowser.Document.Body.ScrollRectangle.Height);
            m_WebBrowser.ScrollBarsEnabled = false;
            m_Bitmap = new Bitmap(m_WebBrowser.Document.Body.ScrollRectangle.Width, m_WebBrowser.Document.Body.ScrollRectangle.Height);
            m_WebBrowser.BringToFront();
            m_WebBrowser.DrawToBitmap(m_Bitmap, m_WebBrowser.Document.Body.ScrollRectangle);


            m_Bitmap = (Bitmap)m_Bitmap.GetThumbnailImage(m_Bitmap.Width, m_Bitmap.Height, null, IntPtr.Zero);
        }

  下面是打开openfiledialog然后输出html流之后来调用上面函数:

 OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.InitialDirectory = "c:\\";//注意这里写路径时要用c:\\而不是c:\
            openFileDialog.Filter = "文本文件|*.*|C#文件|*.cs|所有文件|*.*";
            openFileDialog.RestoreDirectory = true;
            openFileDialog.FilterIndex = 1;
            
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                string fName = openFileDialog.FileName;
                FileStream fs = new FileStream(fName, FileMode.OpenOrCreate, FileAccess.Read);
                StreamReader sr = new StreamReader(fs, Encoding.Default);
                richTextBox1.Text = sr.ReadToEnd();
                this.textBox2.Text = openFileDialog.FileName;
            }

  这个是在点击打开某个文件,包括http格式的超链接都能解析成为StreamReader流,然后通过下面两句来调用最新的函数:

  webBrowser1.Navigate(this.textBox2.Text);
            
            //FormatTableToImage(richTextBox1.Text);
            FormatHtmlToImage(richTextBox1.Text);
然后是FormatHtmlToImage来批量转换多个图片:

 /// <summary>
        /// 单个html,生成图片用
        /// </summary>
        /// <param name="html">匹配的html</param>
        /// <param name="articleId">文章id</param>
        /// <returns></returns>
        private string FormatHtmlToImage(string html)
        {
            string articleId = "imageName";
           
            int i = 0;
            

                string tableHtml = html;

                if (!string.IsNullOrEmpty(tableHtml))
                {

                    string savePath = "d:\\";

                    Bitmap m_Bitmap = GetWebSiteThumbnail(tableHtml, 580, 10);
                    if (m_Bitmap != null)
                    {
                        m_Bitmap.Save("a1.jpg");
                    }

                    i++;
                }
            
       
            return html;
        }

这边是把html或者aspx文件单独存放来转换的,如果大家觉得这样太麻烦,可以定义<table id="1">以及用<table id="1">然后用类似下面的正则来匹配出来,这样就能放在一个aspx或者html来截取图片了。

            string regex1 = "<table id=\"1\"[^>]*>[\\s\\S]*</table id=\"1\">";
            string regex2 = "<table id=\"2\"[^>]*>[\\s\\S]*</table id=\"2\">";
            string regex3 = "<table id=\"3\"[^>]*>[\\s\\S]*</table id=\"3\">";

最后一种情形,如果不是用openfiledialog来手动打开文件或者超文本,那通过写成配置的方式也能使用,把红色的文字换成绿色就行。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值