C#实现HTML转图片(网页快照)
有时候我们需要将网页转成图片,那么可以使用WebBrowser来生成网页快照,废话不多说,代码如下
1、网页快照帮助类(如果是BS或控制台需要引用System.Windows.Forms类库):
1 public class WebSnapshotsHelper 2 { 3 Bitmap m_Bitmap; 4 string m_Url; 5 int m_BrowserWidth, m_BrowserHeight, m_ThumbnailWidth, m_ThumbnailHeight; 6 public WebSnapshotsHelper(string Url, int BrowserWidth, int BrowserHeight, int ThumbnailWidth, int ThumbnailHeight) 7 { 8 m_Url = Url; 9 m_BrowserHeight = BrowserHeight; 10 m_BrowserWidth = BrowserWidth; 11 m_ThumbnailWidth = ThumbnailWidth; 12 m_ThumbnailHeight = ThumbnailHeight; 13 } 14 public static Bitmap GetWebSiteThumbnail(string Url, int BrowserWidth, int BrowserHeight, int ThumbnailWidth, int ThumbnailHeight) 15 { 16 WebSnapshotsHelper thumbnailGenerator = new WebSnapshotsHelper(Url, BrowserWidth, BrowserHeight, ThumbnailWidth, ThumbnailHeight); 17 return thumbnailGenerator.GenerateWebSiteThumbnailImage(); 18 } 19 public Bitmap GenerateWebSiteThumbnailImage() 20 { 21 Thread m_thread = new Thread(new ThreadStart(_GenerateWebSiteThumbnailImage)); 22 m_thread.SetApartmentState(ApartmentState.STA); 23 m_thread.Start(); 24 m_thread.Join(); 25 return m_Bitmap; 26 } 27 private void _GenerateWebSiteThumbnailImage() 28 { 29 WebBrowser m_WebBrowser = new WebBrowser(); 30 m_WebBrowser.ScrollBarsEnabled = false; 31 m_WebBrowser.Navigate(m_Url); 32 m_WebBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted); 33 while (m_WebBrowser.ReadyState != WebBrowserReadyState.Complete) 34 Application.DoEvents(); 35 m_WebBrowser.Dispose(); 36 } 37 private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) 38 { 39 WebBrowser m_WebBrowser = (WebBrowser)sender; 40 m_WebBrowser.ClientSize = new Size(this.m_BrowserWidth, this.m_BrowserHeight); 41 m_WebBrowser.ScrollBarsEnabled = false; 42 m_Bitmap = new Bitmap(m_WebBrowser.Bounds.Width, m_WebBrowser.Bounds.Height); 43 m_WebBrowser.BringToFront(); 44 m_WebBrowser.DrawToBitmap(m_Bitmap, m_WebBrowser.Bounds); 45 m_Bitmap = (Bitmap)m_Bitmap.GetThumbnailImage(m_ThumbnailWidth, m_ThumbnailHeight, null, IntPtr.Zero); 46 } 47 48 }
2、调用:
1 Bitmap m_Bitmap = WebSnapshotsHelper.GetWebSiteThumbnail("http://www.cnblogs.com/", 800, 1200, 800, 1200); //宽高根据要获取快照的网页决定 2 m_Bitmap.Save("render_img.bmp", System.Drawing.Imaging.ImageFormat.Bmp); //图片格式可以自由控制
3、效果:
这个可以在 html页面以一张图片为背景,在其中填空,最后调用此Helper方法来生成图片。
最后说一下:这个使用的是WebBrowser为核心,所以生成的html会根据IE内核来渲染,如果页面中使用到了HTML5、CSS3,那推荐部署的服务器装有IE10及以上浏览器,由于是在服务端生成,对客户端浏览器是没有限制。