Recently, a web project requires that a program capture a Web page. For example:
In test. put a textbox and a button on the ASPX page. the textbox is used to enter the URL of the webpage to be crawled. After the button is pressed, the server needs to capture the previous URL and display it. I made the business logic of image capturing into a class:
Using system;
Using system. Data;
Using system. Windows. forms;
Using system. drawing;
/// <Summary>
/// WebSnap: A web page capturing object
/// </Summary>
Public class websnap2
{
Public websnap2 ()
{
//
// Todo: add the constructor logic here
//
}
/// <Summary>
/// Start a captured image and return the image
/// </Summary>
/// <Param name = "url"> URL of the webpage to be crawled </param>
/// <Returns> </returns>
Public bitmap startsnap (string URL)
{
Webbrowser mywb = This. getpage (URL );
Bitmap returnvalue = This. snapweb (mywb );
Mywb. Dispose ();
Return returnvalue;
}
Private webbrowser getpage (string URL)
{
Webbrowser mywb = new webbrowser ();
Mywb. scrollbarsenabled = false;
Mywb. navigate (URL );
While (mywb. readystate! = Webbrowserreadystate. Complete)
{
System. Windows. Forms. application. doevents ();
}
Return mywb;
}
Private bitmap snapweb (webbrowser WB)
{
Htmldocument Hd = WB. Document;
Int Height = convert. toint32 (HD. Body. getattribute ("scrollheight") + 10;
Int width = convert. toint32 (HD. Body. getattribute ("scrollwidth") + 10;
WB. Height = height;
WB. width = width;
Bitmap BMP = new Bitmap (width, height );
Rectangle rec = new rectangle ();
Rec. width = width;
Rec. Height = height;
WB. drawtobitmap (BMP, REC );
Return BMP;
}
}
Call the following in the button_click event of test. asp:
WebSnap ws = new WebSnap();
Bitmap bmp= ws.StartSnap(TextBox1.Text);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
Response.BinaryWrite(ms.GetBuffer());