C#实现网页截图成果

时间:2022-03-16 07:53:37

网页截图是很常见的实用成果,今天就为大家共享一个实现浏览器截图的代码,主要措施代码如下所示:

private void Form_Load(object sender, EventArgs e) { //接收web url string colle = string.Empty; string url = string.Empty; //获取进程挪用传入的命令 string[] args = Environment.GetCommandLineArgs(); string[] args = new string[] { @"E:\MicroSpace\MicroSpace\localpage\Debug\GetCutImage.exe", "-u:","-n:E:\\TEST\\test.jpg" }; for (int i = 1; i < args.Length; i++) { switch (args[i].Substring(0, 3)) { case "-u:": url = args[i].Substring(3); break; case "-n:": imagename = args[i].Substring(3); break; default: colle = args[i]; break; } } WebBrowser webBrowser = new WebBrowser(); // 创建一个WebBrowser webBrowser.ScrollBarsEnabled = false; // 隐藏滚动条 webBrowser.Navigate(url); // 打开网页 webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser_DocumentCompleted); // 增加网页加载完成事件措置惩罚惩罚函数 } private void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { WebBrowser webBrowser = (WebBrowser)sender; // 网页加载完毕才生存 if (webBrowser.ReadyState == WebBrowserReadyState.Complete) { bool save_suc = true; try { // 获取网页高度和宽度,也可以本身设置 int height = webBrowser.Document.Body.ScrollRectangle.Height; int width = webBrowser.Document.Body.ScrollRectangle.Width; //截图宽度、高度 int imgwidth = width - 2 * 60; int imgheight = height - 48; // 调治webBrowser的高度和宽度 webBrowser.Height = height; webBrowser.Width = width; Bitmap bitmap = new Bitmap(width, height); // 创建高度和宽度与网页不异的图片 Rectangle rectangle = new Rectangle(0, 0, width, height); // 绘图区域 //Rectangle mm=new Rectangle( webBrowser.DrawToBitmap(bitmap, rectangle); // 绘制浏览器图片至bitmap int bmpw = bitmap.Width; int bmph = bitmap.Height; System.Drawing.Image Imag = new System.Drawing.Bitmap(imgwidth, imgheight);//创建Image System.Drawing.Graphics gp = System.Drawing.Graphics.FromImage(Imag);//获取Image的Graphics //通过Graphics绘图实现截图效果 gp.DrawImage(bitmap,new Rectangle(0,0,imgwidth,imgheight),new Rectangle(60,48,imgwidth,imgheight),GraphicsUnit.Pixel); //生存 Imag.Save(imagename, System.Drawing.Imaging.ImageFormat.Jpeg); //bitmap.Save(imagename, System.Drawing.Imaging.ImageFormat.Jpeg); bitmap.Dispose(); gp.Dispose(); Imag.Dispose(); } catch (Exception ex) { } finally { this.Dispose(true); System.Diagnostics.Process.GetCurrentProcess().Kill(); this.Close(); Application.Exit(); } } } //图片生存方法 //imagename 图片路径 bitmap.Save(imagename, System.Drawing.Imaging.ImageFormat.Jpeg); Image.Save(imagename, System.Drawing.Imaging.ImageFormat.Jpeg);

感兴趣的读者还可以按照自身项目需求进一步加以改造,,使之成果越发完善。