asp.net实现将整个网页变成一张图片
C# code
一、实现方法
//WebSiteThumbnail.cs文件,在BS项目中需要添加对System.Windows.Forms的引用
usingSystem;
usingSystem.Data;
usingSystem.Configuration;
usingSystem.Web;
usingSystem.Web.Security;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingSystem.Web.UI.WebControls.WebParts;
usingSystem.Web.UI.HtmlControls;
usingSystem.Drawing;
usingSystem.Threading;
usingSystem.Windows.Forms;
namespaceTestWebApp
{
publicclassWebSiteThumbnail
{
Bitmap m_Bitmap;
string m_Url;
int m_BrowserWidth, m_BrowserHeight, m_ThumbnailWidth, m_ThumbnailHeight;
publicWebSiteThumbnail(stringUrl,intBrowserWidth,intBrowserHeight,intThumbnailWidth,intThumbnailHeight)
{
m_Url =Url;
m_BrowserHeight =BrowserHeight;
m_BrowserWidth =BrowserWidth;
m_ThumbnailWidth =ThumbnailWidth;
m_ThumbnailHeight =ThumbnailHeight;
}
publicstaticBitmapGetWebSiteThumbnail(stringUrl,intBrowserWidth,intBrowserHeight,intThumbnailWidth,intThumbnailHeight)
{
WebSiteThumbnail thumbnailGenerator =newWebSiteThumbnail(Url,BrowserWidth,BrowserHeight,ThumbnailWidth,ThumbnailHeight);
return thumbnailGenerator.GenerateWebSiteThumbnailImage();
}
publicBitmapGenerateWebSiteThumbnailImage()
{
Thread m_thread =newThread(newThreadStart(_GenerateWebSiteThumbnailImage));
m_thread.SetApartmentState(ApartmentState.STA);
m_thread.Start();
m_thread.Join();
return m_Bitmap;
}
privatevoid _GenerateWebSiteThumbnailImage()
{
WebBrowser m_WebBrowser =newWebBrowser();
m_WebBrowser.ScrollBarsEnabled=false;
m_WebBrowser.Navigate(m_Url);
m_WebBrowser.DocumentCompleted+=newWebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);
while(m_WebBrowser.ReadyState!=WebBrowserReadyState.Complete)
Application.DoEvents();
m_WebBrowser.Dispose();
}
privatevoid WebBrowser_DocumentCompleted(object sender,WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser m_WebBrowser =(WebBrowser)sender;
m_WebBrowser.ClientSize=newSize(this.m_BrowserWidth,this.m_BrowserHeight);
m_WebBrowser.ScrollBarsEnabled=false;
m_Bitmap =newBitmap(m_WebBrowser.Bounds.Width, m_WebBrowser.Bounds.Height);
m_WebBrowser.BringToFront();
m_WebBrowser.DrawToBitmap(m_Bitmap, m_WebBrowser.Bounds);
m_Bitmap =(Bitmap)m_Bitmap.GetThumbnailImage(m_ThumbnailWidth, m_ThumbnailHeight,null,IntPtr.Zero);
}
}
}
二、调用方法
//在任意网页中的Page_Load事件时,加入如下代码:
protectedvoid Page_Load(object sender,EventArgs e)
{
Bitmap m_Bitmap =WebSiteThumbnail.GetWebSiteThumbnail("http://www.google.cn",600,600,600,600);
MemoryStream ms =newMemoryStream();
m_Bitmap.Save(ms,System.Drawing.Imaging.ImageFormat.Png);//JPG、GIF、PNG等均可
byte[] buff = ms.ToArray();
Response.BinaryWrite(buff);
}
来自:http://www.itstrike.cn/Question/38733ddb-c15d-44a2-9e2c-e2cc74eeb9d2