Use the webbrowser class in a web project -- capture images for a website

Source: Internet
Author: User

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());

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.