Ramani Sandeep's Blog

DotNetting – Fast , Easy Way of Developing Applications

Capture web page as image using ASP.NET

Posted by Ramani Sandeep on December 5, 2009

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

Advertisement

14 Responses to “Capture web page as image using ASP.NET”

  1. Raymond said

    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

    • Ramani Sandeep said

      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

      • Raymond said

        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

      • Raymond said

        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. Raymond said

    Hi Ramani,

    Can you post your working project here for download? Thank you.

  3. Paresh Dudhat said

    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)…

  4. jcnet said

    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.

  5. Merry said

    You can use http://www.w3snapshot.com to generate website thumbnails.

  6. ali said

    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.

  7. Sandeepan said

    I guess I am also facing similar output as ali is getting.
    I was wondering to get the C# code for the cutycap, but of no help.

    http://cutycapt.sourceforge.net/

    if anyone having a solution for the same or some alternate solution, please let me know.

    thanks

  8. Sandeepan said

    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.

  9. Ebin said

    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?

  10. prashanth said

    while i am execute the code i got server error that is The system cannot find the file specified ,what is that

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 )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

Join 37 other followers