.net mvc C#生成网页快照

目标:调用某一网页,自动抓取整个页面为图片,并保存

 

 public class WebSiteThumbnail
    {
        Bitmap m_Bitmap;
        string m_Url;
        public WebSiteThumbnail(string Url)
        {
            m_Url = Url;
           
        }
        public static Bitmap GetWebSiteThumbnail(string Url)
        {
            WebSiteThumbnail thumbnailGenerator = new WebSiteThumbnail(Url);
            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()
        {
            WebBrowser m_WebBrowser = new WebBrowser();
            m_WebBrowser.ScrollBarsEnabled = false;
            m_WebBrowser.Navigate(m_Url);
            m_WebBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);
            while (m_WebBrowser.ReadyState != WebBrowserReadyState.Complete)
                Application.DoEvents();
            m_WebBrowser.Dispose();
        }
        private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            WebBrowser m_WebBrowser = (WebBrowser)sender;
            //取得页面宽度和高度
            var w = m_WebBrowser.Document.Body.ScrollRectangle.Width;
            var h = m_WebBrowser.Document.Body.OffsetRectangle.Bottom;
            //执行.js出错时任执行
            m_WebBrowser.ScriptErrorsSuppressed = true;
            m_WebBrowser.ClientSize = new Size(w,h);
            m_WebBrowser.ScrollBarsEnabled = false;
            m_Bitmap = new Bitmap(w,h);
            m_WebBrowser.BringToFront();
            m_WebBrowser.DrawToBitmap(m_Bitmap, m_WebBrowser.Bounds);
            m_Bitmap = (Bitmap)m_Bitmap.GetThumbnailImage(w,h, null, IntPtr.Zero);
        }

    }
public ActionResult Index()
        {
            var url = "/home/show";

            var rnd=new Random();
            var saveurl =Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory,"downpic",rnd.Next(10)+".jpg");
            Bitmap m_Bitmap = WebSiteThumbnail.GetWebSiteThumbnail(url);
            m_Bitmap.Save(saveurl, System.Drawing.Imaging.ImageFormat.Png);//JPG、GIF、PNG等均可

            ViewBag.url = "/downpic/" + Path.GetFileName(saveurl);
            return View();
        }

经测试 有一些网站无法生成快照或空白,以后研究

posted @ 2019-01-01 11:14  lunawzh  阅读(519)  评论(1编辑  收藏  举报