Winform将网页生成图片

今天无意见看到浏览器有将网页生成图片的功能,顿时赶脚很好奇,于是就找了找资料自己做了一个类似的功能。

工具截图:生成后的图片

手动填写网站地址,可选择图片类型和保持图片地址,来生成页面的图片,当图片路径未选择时则保存桌面;

具体代码如下:

将html生成图片的类

  1 using System;
  2 using System.Collections.Generic;
  3 using System.ComponentModel;
  4 using System.Data;
  5 using System.Drawing;
  6 using System.Text;
  7 using System.Windows.Forms;
  8 using System.Drawing.Imaging;
  9 using System.Runtime.InteropServices;
 10 using System.Security;
 11 namespace Print
 12 {
 13     public class Test
 14     {
 15         public static Bitmap GetHtmlImage(Uri UrlString, int Width)
 16         {
 17             WebBrowser MyControl = new WebBrowser();
 18             MyControl.Size = new Size(Width, 10);
 19             MyControl.Url = UrlString;
 20             while (MyControl.ReadyState != WebBrowserReadyState.Complete)
 21             {
 22                 Application.DoEvents();
 23             }
 24             MyControl.Height = MyControl.Document.Body.ScrollRectangle.Height + 20;
 25             MyControl.Url = UrlString;
 26             WebControlImage.Snapshot snap = new WebControlImage.Snapshot();
 27             Bitmap MyImage = snap.TakeSnapshot(MyControl.ActiveXInstance, new Rectangle(0, 0, MyControl.Width, MyControl.Height));
 28             MyControl.Dispose();
 29             return MyImage;
 30         }
 31         ///
 32         /// WebBrowser获取图形
 33         ///
 34         private class WebControlImage
 35         {
 36             internal static class NativeMethods
 37             {
 38                 [StructLayout(LayoutKind.Sequential)]
 39                 public sealed class tagDVTARGETDEVICE
 40                 {
 41                     [MarshalAs(UnmanagedType.U4)]
 42                     public int tdSize;
 43                     [MarshalAs(UnmanagedType.U2)]
 44                     public short tdDriverNameOffset;
 45                     [MarshalAs(UnmanagedType.U2)]
 46                     public short tdDeviceNameOffset;
 47                     [MarshalAs(UnmanagedType.U2)]
 48                     public short tdPortNameOffset;
 49                     [MarshalAs(UnmanagedType.U2)]
 50                     public short tdExtDevmodeOffset;
 51                 }
 52                 [StructLayout(LayoutKind.Sequential)]
 53                 public class COMRECT
 54                 {
 55                     public int left;
 56                     public int top;
 57                     public int right;
 58                     public int bottom;
 59                     public COMRECT()
 60                     {
 61                     }
 62                     public COMRECT(Rectangle r)
 63                     {
 64                         this.left = r.X;
 65                         this.top = r.Y;
 66                         this.right = r.Right;
 67                         this.bottom = r.Bottom;
 68                     }
 69                     public COMRECT(int left, int top, int right, int bottom)
 70                     {
 71                         this.left = left;
 72                         this.top = top;
 73                         this.right = right;
 74                         this.bottom = bottom;
 75                     }
 76                     public static NativeMethods.COMRECT FromXYWH(int x, int y, int width, int height)
 77                     {
 78                         return new NativeMethods.COMRECT(x, y, x + width, y + height);
 79                     }
 80                     public override string ToString()
 81                     {
 82                         return string.Concat(new object[] { "Left = ", this.left, " Top ", this.top, " Right = ", this.right, " Bottom = ", this.bottom });
 83                     }
 84                 }
 85                 [StructLayout(LayoutKind.Sequential)]
 86                 public sealed class tagLOGPALETTE
 87                 {
 88                     [MarshalAs(UnmanagedType.U2)]
 89                     public short palVersion;
 90                     [MarshalAs(UnmanagedType.U2)]
 91                     public short palNumEntries;
 92                 }
 93             }
 94             public class Snapshot
 95             {
 96                 ///
 97                 /// ?煺?
 98                 ///
 99                 /// Com 对象
100                 /// 图象大小
101                 ///
102                 public Bitmap TakeSnapshot(object pUnknown, Rectangle bmpRect)
103                 {
104                     if (pUnknown == null)
105                         return null;
106                     //必须为com对象
107                     if (!Marshal.IsComObject(pUnknown))
108                         return null;
109                     //IViewObject 接口
110                     UnsafeNativeMethods.IViewObject ViewObject = null;
111                     IntPtr pViewObject = IntPtr.Zero;
112                     //内存图
113                     Bitmap pPicture = new Bitmap(bmpRect.Width, bmpRect.Height);
114                     Graphics hDrawDC = Graphics.FromImage(pPicture);
115                     //获取接口
116                     object hret = Marshal.QueryInterface(Marshal.GetIUnknownForObject(pUnknown),
117                     ref UnsafeNativeMethods.IID_IViewObject, out pViewObject);
118                     try
119                     {
120                         ViewObject = Marshal.GetTypedObjectForIUnknown(pViewObject, typeof(UnsafeNativeMethods.IViewObject)) as UnsafeNativeMethods.IViewObject;
121                         //调用Draw方法
122                         ViewObject.Draw((int)System.Runtime.InteropServices.ComTypes.DVASPECT.DVASPECT_CONTENT,
123                         -1,
124                         IntPtr.Zero,
125                         null,
126                         IntPtr.Zero,
127                         hDrawDC.GetHdc(),
128                         new NativeMethods.COMRECT(bmpRect),
129                         null,
130                         IntPtr.Zero,
131                         0);
132                     }
133                     catch (Exception ex)
134                     {
135                         Console.WriteLine(ex.Message);
136                         throw ex;
137                     }
138                     //释放
139                     hDrawDC.Dispose();
140                     return pPicture;
141                 }
142             }
143             [SuppressUnmanagedCodeSecurity]
144             internal static class UnsafeNativeMethods
145             {
146                 public static Guid IID_IViewObject = new Guid("{0000010d-0000-0000-C000-000000000046}");
147                 [ComImport, Guid("0000010d-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
148                 public interface IViewObject
149                 {
150                     [PreserveSig]
151                     int Draw([In, MarshalAs(UnmanagedType.U4)] int dwDrawAspect, int lindex, IntPtr pvAspect, [In] NativeMethods.tagDVTARGETDEVICE ptd, IntPtr hdcTargetDev, IntPtr hdcDraw, [In] NativeMethods.COMRECT lprcBounds, [In] NativeMethods.COMRECT lprcWBounds, IntPtr pfnContinue, [In] int dwContinue);
152                     [PreserveSig]
153                     int GetColorSet([In, MarshalAs(UnmanagedType.U4)] int dwDrawAspect, int lindex, IntPtr pvAspect, [In] NativeMethods.tagDVTARGETDEVICE ptd, IntPtr hicTargetDev, [Out] NativeMethods.tagLOGPALETTE ppColorSet);
154                     [PreserveSig]
155                     int Freeze([In, MarshalAs(UnmanagedType.U4)] int dwDrawAspect, int lindex, IntPtr pvAspect, [Out] IntPtr pdwFreeze);
156                     [PreserveSig]
157                     int Unfreeze([In, MarshalAs(UnmanagedType.U4)] int dwFreeze);
158                     void SetAdvise([In, MarshalAs(UnmanagedType.U4)] int aspects, [In, MarshalAs(UnmanagedType.U4)] int advf, [In, MarshalAs(UnmanagedType.Interface)] System.Runtime.InteropServices.ComTypes.IAdviseSink pAdvSink);
159                     void GetAdvise([In, Out, MarshalAs(UnmanagedType.LPArray)] int[] paspects, [In, Out, MarshalAs(UnmanagedType.LPArray)] int[] advf, [In, Out, MarshalAs(UnmanagedType.LPArray)] System.Runtime.InteropServices.ComTypes.IAdviseSink[] pAdvSink);
160                 }
161             }
162         }
163     }
164 }

winfrom后台处理方面代码如下

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using System.Linq;
 7 using System.Text;
 8 using System.Windows.Forms;
 9 using System.Drawing.Imaging;
10
11 namespace Excel文件处理
12 {
13     public partial class Html : Form
14     {
15         public Html()
16         {
17             InitializeComponent();
18         }
19         private string ImageUrl = "";//图片地址
20         private string ImageName = "";//图片名称
21         private void button1_Click(object sender, EventArgs e)
22         {
23             string HtmlUrl = this.Txt_Url.Text.Trim();
24             if (HtmlUrl=="")
25             {
26                 MessageBox.Show("请输入网址");
27                 return;
28             }
29             if (ImageUrl.Trim()=="")
30             {
31                 ImageUrl = @"C:\Users\Administrator\Desktop";
32             }
33             try
34             {
35                 Uri ri = new Uri(this.Txt_Url.Text);
36                 Bitmap bit = Print.Test.GetHtmlImage(ri, 1200);
37                 ImageName = this.Txt_Name.Text.Trim();//图片名称
38                 if (ImageName != "")
39                 {
40                     if (ImageName.IndexOf(‘.‘) != -1)
41                     {//当用户输入图片后缀时,将后缀截取
42                         ImageName.Substring(0, ImageName.LastIndexOf(‘.‘));
43                     }
44                 }
45                 else
46                     ImageName = DateTime.Now.Ticks.ToString();//时间名称
47                 switch (this.comboBox1.SelectedText)
48                 {
49                     case "GIF": ImageUrl += "\\" + ImageName + ".gif"; break;
50                     case "JPG": ImageUrl += "\\" + ImageName + ".jpg"; break;
51                     case "PNG": ImageUrl += "\\" + ImageName + ".png"; break;
52                     default: ImageUrl += "\\" + ImageName + ".png"; break;
53                 }
54
55                 switch (this.comboBox1.SelectedText)
56                 {
57                     case "GIF": bit.Save(ImageUrl, ImageFormat.Gif); break;
58                     case "JPG": bit.Save(ImageUrl, ImageFormat.Jpeg); break;
59                     case "PNG": bit.Save(ImageUrl, ImageFormat.Png); break;
60                     default: bit.Save(ImageUrl, ImageFormat.Png); break;
61                 }
62
63                 bit = null;
64                 ImageUrl = "";//图片地址
65                 ImageName = "";//图片名称
66                 MessageBox.Show("生产成功");
67             }
68             catch
69             {
70                 MessageBox.Show("网址输入有误!");
71                 return;
72             }
73
74         }
75
76         private void button2_Click(object sender, EventArgs e)
77         {
78             //获取保存路径
79             if (this.folderBrowserDialog1.ShowDialog()==DialogResult.OK)
80             {
81                 if (this.folderBrowserDialog1.SelectedPath.Trim()!="")
82                 {
83                     ImageUrl = folderBrowserDialog1.SelectedPath;
84                     this.label6.Text = ImageUrl;
85                 }
86             }
87
88         }
89     }
90 }
时间: 2024-10-07 01:54:02

Winform将网页生成图片的相关文章

网页生成图片快照

网页生成图片快照 源码地址:https://github.com/juforg/websnapasimg 调用 请求地址 测试环境:http://localhost:7090/htmlsnapshot/snaphtml调用方式 GET 参数名 说明 htmlUrl 需要将response的html进行截图的请求地址,需要URLEncoder.encode(htmlUrl,"UTF-8") imgType 生成图片的类型 如:PNG,GIF,JPG,BMP,RAF 保存返回的图片流 Ht

C# Winform利用POST传值方式模拟表单提交数据(Winform与网页交互)

其原理是,利用winfrom模拟表单提交数据,将要提交的参数提交给网页,网页执行代码,得到数据,然后Winform程序将网页的所有源代码读取下来,这样就达到windows应用程序和web应用程序之间传参和现实数据的效果了. - 首先创建一个windows应用程序和web应用程序. - 在web应用程序中,将网页切换到源代码并把源代码中一些没用的代码删掉,只保留头部,在windows应用程序读取网页源码时,这些都会被一起读下来,但这些都是没用的数据,而且删掉没什么影响.需要保留的代码如下: - <

解决 winform打开网页 和WebBrowser打开链接360误报拦截的问题

以下方法我已经在自己电脑上验证通过,其他电脑并未测试,请广大读者自行验证并反馈,如果有更好的方法请指教. 在winform中如果使用这种方法弹出网页,例如这样 Process.start("http://www.xgjxc.top"); 或者另外如果winform中嵌入了一个webbrowser控件,加载了一个网页,例如这样 this.webBrowser1.Navigate("http://www.xgjxc.top/home.html“); 网页中有个超链接,例如这样 &

C# Html网页生成图片解决方案1

1.使用System.Windows.Forms命名空间下的WebBrowser控件加载网页并生成图片 GiHub参考地址: https://github.com/tianma3798/FileOparate/ 使用方法: public static void TestOne() { ThumbnailImg img = new ThumbnailImg("e:\\one.png"); //img.SetToJpeg(); //img.SetToGif(); ThumbnailOper

winform截取网页邮箱

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Threadin

html2canvas.js网页截图功能

需求:将网页生成图片,用户自行长按图片进行保存图片,再分享朋友圈.其中,都可识别图中的二维码.(二维码过小会识别不出) 首先,先来科普一下微信网页识别二维码原理:截屏识别,当客户端发现用户在网页的img标签内进行长按操作时,会立刻截屏并且启动二维码识别算法.https://www.cnblogs.com/daipi... 发现官网中的html2canvas.js插件存在一些bug: 1.截图不全,不完整 解决方案: //修改源码,添加自定设置高度宽度 var width = options.wi

C# WebBrowser控件使用整理

一.简介 WebBrowser 控件为 WebBrowser ActiveX 控件提供了托管包装. 托管包装使您可以在 Windows 窗体客户端应用程序中显示网页. 使用WebBrowser 控件,可以复制应用程序中的 Internet Explorer Web 浏览功能,还可以禁用默认的 Internet Explorer 功能,并将该控件用作简单的 HTML 文档查看器. 此外,可以使用该控件将基于 DHTML 的用户界面元素添加到窗体中,还可以隐瞒这些元素在 WebBrowser 控件中

WPF 杂谈——资源文件

编写一个应用难免要用到WPF本身的控件.不管是WinForm还是网页都会有自己的控件.只是在写法和用法上有所不同而以.而控件命名却离不开那几个单词.所以不用担心判断不出来哪个是按扭,哪个是文本框.举个例子吧. HTML <input type="button" value="扭按" /> WinForm private System.Windows.Forms.Button button1; WPF <Button Content="按扭

winform里面打开网页,以及意想不到的功能

首先,新建一个winform项目,我在想,如果想要实现打开网页功能的话,应该会有一个控件什么之类的吧?查了工具栏,真的有一个名叫 WebBrowser的家伙,应该就是这货没错了.在网上查了它的资料更加坚定了我的判断,二话不说,拖进Form里.接着,就是要显示一个网页了,要怎 么实现呢?继续查看WebBrowser都有啥属性和方法: 方法 说明 GoBack 相当于IE的“后退”按钮,使你在当前历史列表中后退一项 GoForward 相当于IE的“前进”按钮,使你在当前历史列表中前进一项 GoHo