C#生成网页缩略图来源: 发布时间:星期一, 2008年7月28日 浏览:1236次 评论:0
C#生成网页缩略图的方法,我们需要采用WebBrower控件 废话少说,看代码 原理其实是在请求页面加载完毕后触发缩略图生成事件,生成显示回来的数据 private void OnDocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { WebBrowser browser = (sender as WebBrowser); if (browser != null) { mshtml.IHTMLDocument2 document = (browser.Document.DomDocument as mshtml.IHTMLDocument2); if (document != null) { mshtml.IHTMLElement element = (document.body as mshtml.IHTMLElement); if (element != null) { IHTMLElementRender render = (element as IHTMLElementRender); if (render != null) { using (Graphics graphics = this.CreateGraphics()) { IntPtr hdcDestination = graphics.GetHdc(); render.DrawToDC(hdcDestination); IntPtr hdcMemory = GDI32.CreateCompatibleDC(hdcDestination); IntPtr bitmap = GDI32.CreateCompatibleBitmap( hdcDestination, browser.ClientRectangle.Width, browser.ClientRectangle.Height ); if (bitmap != IntPtr.Zero) { IntPtr hOld = (IntPtr)GDI32.SelectObject(hdcMemory, bitmap); GDI32.BitBlt( hdcMemory, 0, 0, browser.ClientRectangle.Width, browser.ClientRectangle.Height, hdcDestination, 0, 0, TernaryRasterOperations.SRCCOPY ); GDI32.SelectObject(hdcMemory, hOld); GDI32.DeleteDC(hdcMemory); graphics.ReleaseHdc(hdcDestination); SaveThumbnail(Image.FromHbitmap(bitmap)); } } } } } } } 从这里获取了内容的话,我们就很容易生成缩略图了,代码如下 //by crazycoder.cn private void SaveThumbnail(Image image) { if (image != null) {//创建一个位图图像 Bitmap thumbnail = new Bitmap(160, 120, PixelFormat.Format24bppRgb); thumbnail.SetResolution(image.HorizontalResolution, image.VerticalResolution); using (Graphics resize = Graphics.FromImage(thumbnail)) { resize.InterpolationMode = InterpolationMode.HighQualityBicubic; resize.DrawImage(image, new Rectangle(0, 0, 160, 120), new Rectangle(0, 0, _webBrowser.ClientRectangle.Width, _webBrowser.ClientRectangle.Height), GraphicsUnit.Pixel); } thumbnail.Save(_file.FullName, ImageFormat.Png); } } 下载整个项目代码 CrazyCoder_WebPageToImage.zip 6
相关文章读者评论发表评论 |