C#实现在网页中根据url截图并输出到网页的方法
本文实例讲述了C#实现在网页中根据url截图并输出到网页的方法。分享给大家供大家参考,具体如下:
网页截图是很多站点的一个小需求,这段代码实现的是如何根据url获得网页截图并输出到网页中。
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Web;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingSystem.Threading;
usingSystem.Windows.Forms;
usingSystem.Drawing;
usingSystem.IO;
///<summary>
///Thispageshowthewayofgenerateaimageinwebsite
///</summary>
publicpartialclassDefault2:System.Web.UI.Page
{
protectedvoidPage_Load(objectsender,EventArgse)
{
Bitmapm_Bitmap=WebSiteThumbnail.GetWebSiteThumbnail("http://www.google.cn",600,600,600,600);
MemoryStreamms=newMemoryStream();
m_Bitmap.Save(ms,System.Drawing.Imaging.ImageFormat.Png);//JPG、GIF、PNG等均可
byte[]buff=ms.ToArray();
Response.BinaryWrite(buff);
}
}
publicclassWebSiteThumbnail
{
Bitmapm_Bitmap;
stringm_Url;
intm_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)
{
WebSiteThumbnailthumbnailGenerator=newWebSiteThumbnail(Url,BrowserWidth,BrowserHeight,ThumbnailWidth,ThumbnailHeight);
returnthumbnailGenerator.GenerateWebSiteThumbnailImage();
}
publicBitmapGenerateWebSiteThumbnailImage()
{
Threadm_thread=newThread(newThreadStart(_GenerateWebSiteThumbnailImage));
m_thread.SetApartmentState(ApartmentState.STA);
m_thread.Start();
m_thread.Join();
returnm_Bitmap;
}
privatevoid_GenerateWebSiteThumbnailImage()
{
WebBrowserm_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();
}
privatevoidWebBrowser_DocumentCompleted(objectsender,WebBrowserDocumentCompletedEventArgse)
{
WebBrowserm_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);
}
}
希望本文所述对大家C#程序设计有所帮助。