irst we need to add reference of Windows.Forms
In following code snippet, I have created CaptureScreenShot() method with three parameters named url, width and height. In method body, I have initialized a new thread. Then inside the thread, I have created a new WebBrowser control and set properties of the control. We need to start a new thread for WebBrowser control and execute the thread in single threaded apartments because ASP.NET applications work in multithreaded apartments. I have called the Navigate() method to browse the URL. I have attached DocumentCompleted event handler with WebBrowser control which will be raised when web page is loaded in the WebBrowser control. In DecumentCompleted event handler body, I have called DrawToBitmap() method of WebBrowser control to get the bitmap image of the webpage. At the end, I have converted image to Base64 string by using byte array.
Namespaces
|
using System.Windows.Forms;
using System.Threading;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
|
Write following method
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
public void CaptureScreenShot(string url, int width, int height)
{
Thread thread = new Thread(delegate()
{
WebBrowser wb = new WebBrowser();
wb.ScrollBarsEnabled = false;
wb.ScriptErrorsSuppressed = true;
wb.Navigate(url);
wb.Width = width;
wb.Height = height;
wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(DocumentCompleted);
while (wb.ReadyState != WebBrowserReadyState.Complete)
{
System.Windows.Forms.Application.DoEvents();
}
wb.Dispose();
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
}
|
Now write following WebBrowser event handler
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
private void DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser wb = sender as WebBrowser;
using (Bitmap bitmap = new Bitmap(wb.Width, wb.Height))
{
wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height));
using (MemoryStream ms = new MemoryStream())
{
bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
imgCapture.Visible = true;
imgCapture.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(ms.ToArray());
}
}
}
|
At the end, just call the method by providing parameters.
|
CaptureScreenShot("http://getcodesnippet.com/", 1024, 768);
|
You can download entire project code sample from below link.