很多人可能奇怪,网站截图?那是发生在客户端上的啊,而我们所运行的ASP.net程序是运行在服务器端的,这是两台不同的机器啊,怎么可能会截图呢?当然,截图的方式方法很多,最普片的是通过ActiveX在客户端执行,但是,如果除去ActiveX,我们同样可以实现——通过服务器模拟方式。
模拟客户端,也就是说,在服务器端内存中生成一个浏览器对象,通过该虚拟的浏览器访问某个网站,再通过GDI对这个虚拟的浏览器截图。这也就是整个网站截图的思路和原理。
WebBrowser MyBrowser;
//声明浏览器对象
public WebPageBitmap( string url, int width, int height)
{
... ...
//创建浏览器对象
MyBrowser = new WebBrowser();
MyBrowser.ScrollBarsEnabled = false;
MyBrowser.Size = new Size( this.Width, this.Height);
}
public WebPageBitmap( string url, int width, int height)
{
... ...
//创建浏览器对象
MyBrowser = new WebBrowser();
MyBrowser.ScrollBarsEnabled = false;
MyBrowser.Size = new Size( this.Width, this.Height);
}
有了浏览器对象以后,则需要使用该浏览器去访问某个网站
public
void GetIt()
{
MyBrowser.Navigate( this.URL);
while (MyBrowser.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
}
{
MyBrowser.Navigate( this.URL);
while (MyBrowser.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
}
public Bitmap DrawBitmap(
int theight,
int twidth)
{
Bitmap myBitmap = new Bitmap( this.Width, this.Height);
Rectangle DrawRect = new Rectangle(0, 0, this.Width, this.Height);
MyBrowser.DrawToBitmap(myBitmap, DrawRect);
System.Drawing.Image imgOutput = myBitmap;
System.Drawing.Bitmap oThumbNail = new Bitmap(twidth, theight, imgOutput.PixelFormat);
Graphics g = Graphics.FromImage(oThumbNail);
... ...
}
{
Bitmap myBitmap = new Bitmap( this.Width, this.Height);
Rectangle DrawRect = new Rectangle(0, 0, this.Width, this.Height);
MyBrowser.DrawToBitmap(myBitmap, DrawRect);
System.Drawing.Image imgOutput = myBitmap;
System.Drawing.Bitmap oThumbNail = new Bitmap(twidth, theight, imgOutput.PixelFormat);
Graphics g = Graphics.FromImage(oThumbNail);
... ...
}
最后一步,则是使用GDI技术绘制,在这里,我们通过DrawToBitmap方法,直接将浏览器的图像绘制到图像中。