C#实现网页截图功能
网页截图是很常见的实用功能,今天就为大家共享一个实现浏览器截图的代码,主要程序代码如下所示:
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:http://sliefj.com/template/amo.html","-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);
感兴趣的读者还可以根据自身项目需求进一步加以改进,使之功能更加完善。
赞 (0)