Capture web page as image using ASP.NET


Introduction

This article describes how you can take a screenshot of a special webpage programmatically with ASP.NET. The goal of this sample is to find a way to capture a webpage’s image. The parameter is just a special url. Only by knowing this url we want to be able to take a screenshot of this webpage – a bitmap of what the user would see if he/she types this url in the browser.

How to take a screenshot of browser-content?

Here I have used one utility program to take screen shot of browser content name is IECapt.exe. IECapt is a small command-line utility to capture Internet Explorer’s rendering of a web page into a BMP, JPEG or PNG image file. We have to put IECapt.exe on the server and define that we have the right to execute it.

Download IECapt.exe

Here is the sample application for the same.

Step 1: Create the web application with two web page & in first page create screen like this

1

Here is the html for that:

 <table cellpadding="10" cellspacing="0" width="700" style="border-style:solid; background-color:green;">
            <tr>
                <td align="center" colspan="2">
                    <h1>
            Take a Snap of Web page</h1> <hr />
                </td>
            </tr>
            <tr>
                <td align="right">
                    Url:
                </td>
                <td align="left">
                    <asp:TextBox ID="txtUrl" runat="server" Width="300">http://www.ramanisandeep.wordpress.com</asp:TextBox>
                </td>
            </tr>
            <tr>
                <td align="right">
                    Width:
                </td>
                <td align="left">
                    <asp:TextBox ID="txtWidth" runat="server">500</asp:TextBox>
                </td>
            </tr>
            <tr>
                <td align="right">
                    Height:
                </td>
                <td align="left">
                    <asp:TextBox ID="txtHeight" runat="server">500</asp:TextBox>
                </td>
            </tr>
            <tr>
                <td align="right">
                    Save image with this name :
                </td>
                <td align="left">
                    <asp:TextBox ID="txtDestImage" runat="server">MyImage3</asp:TextBox>
                </td>
            </tr>
            <tr>
                <td align="right">
                </td>
                <td align="left">
                    <asp:Button ID="btnCapture" runat="server" OnClick="btnCapture_Click" Text="Capture"
                         />
                </td>
            </tr>
        </table>

Step 2: On Button click event call the class method & redirect to new page to show the image

Code behind would be like this:

 protected void btnCapture_Click(object sender, EventArgs e)
    {
        int Width, Height;
        Width = Convert.ToInt32(txtWidth.Text);
        Height = Convert.ToInt32(txtHeight.Text);
        CaptureWebPage cwp = new CaptureWebPage();
        string imagePath = cwp.GetImage(txtUrl.Text, txtDestImage.Text, Server.MapPath("~"), Width, Height);
        Response.Redirect("~/Default2.aspx?Path=" + imagePath);
    }

Step 3: Create class CaptureWebPage.cs

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Diagnostics;
using System.Drawing.Imaging;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;

public class CaptureWebPage
{
    private const string EXTRACTIMAGE_EXE = "IECapt.exe";
    private const int TIMEOUT = 60000;
    private const string TMP_NAME = "InBetween.png";

    public CaptureWebPage()
    {
    }

    private void Shot(string url, string rootDir)
    {
        Process p = new Process();
        p.StartInfo.FileName = rootDir + "\\" + EXTRACTIMAGE_EXE;
        p.StartInfo.Arguments = String.Format("\"{0}\" \"{1}\"", url, rootDir + "\\" + TMP_NAME);
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.CreateNoWindow = false;
        p.Start();
        p.WaitForExit();
        p.Dispose();
    }

    private System.Drawing.Image Scale(System.Drawing.Image imgPhoto,int Width, int Height)
    {
        int srcWidth = imgPhoto.Width;
        int srcHeight = imgPhoto.Height;
        int srcX = 0; int srcY = 0;
        int destX = 0; int destY = 0;

        float percent = 0; float percentWidth = 0; float percentHeight = 0;

        percentWidth = ((float)Width / (float)srcWidth);
        percentHeight = ((float)Height / (float)srcHeight);

        if (percentHeight < percentWidth)
        {
            percent = percentWidth;
            destY = 0;
        }
        else
        {
            percent = percentHeight;
            destX = 0;
        }

        int destWidth = (int)(srcWidth * percent);
        int destHeight = (int)(srcHeight * percent);

        System.Drawing.Bitmap bmPhoto = new System.Drawing.Bitmap(Width,
                Height, PixelFormat.Format24bppRgb);
        bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
                imgPhoto.VerticalResolution);

        Graphics grPhoto = Graphics.FromImage(bmPhoto);
        grPhoto.InterpolationMode =
                InterpolationMode.HighQualityBicubic;

        grPhoto.DrawImage(imgPhoto,
            new Rectangle(destX, destY, destWidth, destHeight),
            new Rectangle(srcX, srcY, srcWidth, srcHeight),
            GraphicsUnit.Pixel);

        grPhoto.Dispose();
        return bmPhoto;
    }

    public string GetImage(string url, string name, string rootDir,	int width, int height)
    {
        string fileName = rootDir + "\\" + TMP_NAME;
        Shot(url, rootDir);
        System.Drawing.Image thumbImage = System.Drawing.Image.FromFile(fileName);
        Scale(thumbImage, width, height);
        System.Drawing.Image scaledImg = Scale(thumbImage, width, height);
        fileName = rootDir + "\\" + name + ".png";
        if (File.Exists(fileName))
            File.Delete(fileName);
        scaledImg.Save(fileName, ImageFormat.Png);
        return name + ".png";
    }
}

Step 4: Create new page Default2.aspx to display the shot taken

Here is the html for that:

 <asp:Image ID="theImage" runat="server" />
  <asp:Button ID="Button1" runat="server" Text="Go Back" OnClick="Button1_Click" />

Code behind would be:

 protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["Path"] != null)
        {
            theImage.ImageUrl = "~//" + Request.QueryString["Path"].ToString();
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Default.aspx");
    }

Step 5: Most important thing is Download IECapt.exe from the above link & put at the rool level.

Run the Application

2

Great !!!

Now enjoy taking the snap of the web page in your web application when ever required or application demands.

Jay Ganesh

Shout it

kick it on DotNetKicks.com

About these ads

33 thoughts on “Capture web page as image using ASP.NET

  1. Hi Ramani,

    Thank you very much for sharing this with people, I tried your code, however, it is not working as expected, the thumnail can’t be generated but IECapt.exe is working fine in command line.
    I posted my question on VB City, could you take a look? or could you send me a working project? Thank you very much in advance.

    Here is the link of my question on VB City:

    http://vbcity.com/forums/p/161890/692585.aspx#692585

    1. Hi Raymond,

      Code is working for me,
      Now Check this ,
      Have u set the permissions (read/write) full access to the folder in which you are saving you image & try to debug the code & identify where error comes.

      initially i have also faced lots of problem but after it i was able to do it correctly..

      now i can suggest you one more thing.. as this solution is slow it u need to generate lots of page image. so u can also use http://www.pageglimpse.com/ service api & get what u want..

      hope this helps
      thanks

      1. I did set the permission to full control to the built-in account ASPNET, it’s still no use, the inbween.png won’t be generated.

        I believe I’ve adapted all your code in my project, but could you double check it? it’s posted in my question on VB City.

        Thanks again for your help

      2. There is no error generated. To me, it looks like the IECapt is not working because no thumbnail is generated by it, however, it does generate thumbnail in command line. Full permission has been granted to machine\ASPNET account for the website’s folder.

        BTW: the website you recommended is working for me, but I still want to find out why the code works for you but not me, it would be great if you could send me a working package, my email is HardworkingRaymond at Gmail.com, Thanks again for your help.

  2. Hi Ramani…
    I want to make one website for online quiz competition..
    in which at the end of exam i want to print marksheet…
    here i want to put image of student captured using webcam…
    how to do this in asp.net with c#…

    i am from ahmedabad (gujrat)…

  3. iecapt has great potential. But there does not appear to be a way to pass it urls with query strings in them? And because you call it from the servers via Process Start, there is no way to pass it session or form variables either. I’ve tried encoding ? and = with %3D and %3F .. but no luck in IE.

    I’ve emailed the authori, but if anybody has a workaround please let me know.

    Thanks.

  4. Good Post.but a little problem that when i click on capture image it wait for almost many second a dos prompt window display that is i think ICAPT.EXE and then it show another window “An error has occurred in the script on this page” and image will generate in the solution folder.
    ur techincal response is highly appreciated.

  5. Changing the line

    from
    p.StartInfo.Arguments = String.Format(“\”{0}\” \”{1}\””, url, rootDir + “\\” + TMP_NAME);

    to
    p.StartInfo.Arguments = String.Format(“{0} {1}”, “–url=” + url, “–out=” + rootDir + “\\” + TMP_NAME);

    works.
    Also if you want to disable the command window,
    make
    p.StartInfo.CreateNoWindow = true;

    I am just wondering how to reduce the time generate the image.

  6. I tried the code , am not getting any error but the image file created is a white box with a black border .
    Can you tell me what is the problem?

  7. while i am execute the code i got server error that is The system cannot find the file specified ,what is that
    AT
    p.Start();

  8. Hi Ramani,

    Thanks for your post. I was searching for a solution to generate web image. I can able to implement and generate images. But have some issue in my own machine while i try to invoke via IIS. Seems to be hanging for some duration and finally times out.ls this due to some IIS configuration.But all machine has same configuration.Please help me.

  9. Hi Ramani,
    For some reason, I followed your steps and could not get it to debug or run. Below is the error message that I keep getting. Can you help?
    Thanks,
    Mike

    Control ‘txtUrl’ of type ‘TextBox’ must be placed inside a form tag with runat=server.
    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.Web.HttpException: Control ‘txtUrl’ of type ‘TextBox’ must be placed inside a form tag with runat=server.

  10. Hi Ramani,
    For some reason, I followed your steps and could not get it to debug or run. Below is the error message that I keep getting. Can you help?
    Thanks,
    Mike

    Control ‘txtUrl’ of type ‘TextBox’ must be placed inside a form tag with runat=server.
    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.Web.HttpException: Control ‘txtUrl’ of type ‘TextBox’ must be placed inside a form tag with runat=server.

  11. Hi Sandeep,

    When i am using this code, it was captured some part of the page only. How to capture the hole page.

    Thank You

  12. I am developing a website and I want to capture photo through my webcam. kindly tell me coding as I am new to .net and I am using visual basic language

  13. hi,
    i tried with ur code, its working fine..
    but iam using cloud server, this server accept only Medium Trust.
    but your exe not work in Medium Trust..
    can u modify the exe and send it plz…

  14. In my application I’ve to capture the screen shot of the current page passing the URL of current page but problem is that when I wrote the code for capturing screen shot it is giving me the screen shot of home page not the current page, can any one tell me whats the problem.

  15. You want a internet site devoted on the product and to appointing.
    Now when I walk into a room people instantly treat me
    as someone of influence and they don’t even know me. He
    realised that he could develop excellent associations with people
    from all over the world.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s