.net mvc C#生成网页快照

2021-06-23 01:04

阅读:628

标签:bottom   path   drawing   ptr   body   led   enable   index   调用   

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

 

 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();
        }

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

.net mvc C#生成网页快照

标签:bottom   path   drawing   ptr   body   led   enable   index   调用   

原文地址:https://www.cnblogs.com/lunawzh/p/10204367.html


评论


亲,登录后才可以留言!