How to capture screen shot in ASP.NET
by GetCodeSnippet.com • April 22, 2014 • Microsoft .NET C# (C-Sharp), Microsoft ASP.NET, Microsoft VB.NET • 0 Comments
Sometimes we need to take a screen shot of a webpage in our ASP.NET application. There are so many solutions available for this task. Many third party APIs and utilities available but you can simply do it by using ASP.NET built-in classes and objects. If you need to capture screen shot of your current page, you just need to create objects of Bitmap and Graphics classes, copy image from screen and save it to your desired location. It can be done with few lines of code and I will show you this code snippet in this article. In an upcoming article, I will show you how we can capture screen shot for a given URL.
Let’s see the code of capturing screen shot in ASP.NET. You need to add reference of Windows.Forms library.
Create a website in C# or VB.NET
Click on add reference, select .NET tab and add System.Windows.Forms
Add following namespaces
C#
1 2 3 |
using System.Windows.Forms; using System.Drawing; using System.Drawing.Imaging; |
VB.NET
1 2 3 |
Imports System.Windows.Forms Imports System.Drawing Imports System.Drawing.Imaging |
Now look at the following code
C#
1 2 3 4 5 6 7 |
protected void btnCapture_Click(object sender, EventArgs e) { Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height); Graphics graphics = Graphics.FromImage(bitmap as System.Drawing.Image); graphics.CopyFromScreen(0, 0, 0, 0, bitmap.Size); bitmap.Save(@"c:\Images\screenshot.bmp", ImageFormat.Bmp); } |
VB.NET
1 2 3 4 5 6 |
Protected Sub btnCapture_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCapture.Click Dim bitmap As New Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height) Dim graphics1 As Graphics = Graphics.FromImage(TryCast(bitmap, System.Drawing.Image)) graphics1.CopyFromScreen(0, 0, 0, 0, bitmap.Size) bitmap.Save("c:\Images\screenshot.bmp", ImageFormat.Bmp) End Sub |
You can see I have created an object of Bitmap class providing width and height by using Screen class of Windows.Forms. Then I have created a Graphics class object by providing Bitmap class object. I have used CopyFromScreen() method of Graphics class to get the image of the current screen. At the end, I have saved the image.
You can download complete code sample from below link
