C# 将网页保存为图片(利用WebBrowser)

C# 143次浏览 本站
using System;
using System.Drawing;
using System.Windows.Forms;
 
namespace UrlToImage
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            var browser = new WebBrowser {ScrollBarsEnabled = false, ScriptErrorsSuppressed = true};
            browser.Navigate("http://www.rc114.com/");
            browser.DocumentCompleted += webBrowser_DocumentCompleted;
        }
 
        private void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            var browser = (WebBrowser) sender;
            if (browser.ReadyState == WebBrowserReadyState.Complete)
            {
                if (browser.Document != null)
                {
                    if (browser.Document.Body != null)
                    {
                        var height = browser.Document.Body.ScrollRectangle.Height;
                        var width = browser.Document.Body.ScrollRectangle.Width;
                        browser.Height = height;
                        browser.Width = width;
                        using (var bitmap = new Bitmap(width, height))
                        {
                            var rectangle = new Rectangle(0, 0, width, height);
                            browser.DrawToBitmap(bitmap, rectangle);
                            var dialog = new SaveFileDialog();
                            dialog.Filter = " JPEG (*.jpg)|*.jpg|PNG (*.png)|*.png ";
                            dialog.ShowDialog();
                            bitmap.Save(dialog.FileName);
                        }
                    }
                }
            }
        }
    }
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注