首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 網頁截圖核心類(一):WebBrowser 截圖與縮略圖生成

     編輯:關於C語言

需對指定網頁進行截圖並生成指定尺寸縮略圖。本文提供核心類 GetImage 與內部類 WebPageBitmap,基於 WebBrowser 控件實現 1:1 截圖與高質量縮放。

必要引用

  • System.Drawing
  • System.Drawing.Design
  • System.Windows.Forms

核心類完整代碼

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Windows.Forms;
using System.Diagnostics;

namespace MyLib
{
    public class GetImage
    {
        public int ScreenWidth { get; set; }
        public int ScreenHeight { get; set; }
        public int ImageWidth { get; set; }
        public int ImageHeight { get; set; }
        public string WebSite { get; set; }

        public GetImage(string webSite, int screenWidth, int screenHeight, int imageWidth, int imageHeight)
        {
            WebSite = webSite;
            ScreenWidth = screenWidth;
            ScreenHeight = screenHeight;
            ImageWidth = imageWidth;
            ImageHeight = imageHeight;
        }

        public Bitmap GetBitmap()
        {
            WebPageBitmap shot = new WebPageBitmap(WebSite, ScreenWidth, ScreenHeight);
            shot.GetIt();
            return shot.DrawBitmap(ImageHeight, ImageWidth);
        }
    }

    class WebPageBitmap
    {
        WebBrowser browser;
        string url;
        int width, height;

        public WebPageBitmap(string url, int width, int height)
        {
            this.url = url;
            this.width = width;
            this.height = height;
            browser = new WebBrowser { ScrollBarsEnabled = false, Size = new Size(width, height) };
        }

        public void GetIt()
        {
            browser.Navigate(url);
            while (browser.ReadyState != WebBrowserReadyState.Complete)
                Application.DoEvents();
        }

        public Bitmap DrawBitmap(int theight, int twidth)
        {
            Bitmap bitmap = new Bitmap(width, height);
            browser.DrawToBitmap(bitmap, new Rectangle(0, 0, width, height));
            Image thumb = new Bitmap(twidth, theight, bitmap.PixelFormat);
            using (Graphics g = Graphics.FromImage(thumb))
            {
                g.CompositingQuality = CompositingQuality.HighSpeed;
                g.SmoothingMode = SmoothingMode.HighSpeed;
                g.InterpolationMode = InterpolationMode.HighQualityBilinear;
                g.DrawImage(bitmap, new Rectangle(0, 0, twidth, theight));
            }
            bitmap.Dispose();
            browser.Dispose();
            return (Bitmap)thumb;
        }
    }
}

使用說明

實例化 GetImage 傳入 URL、瀏覽器視窗大小、輸出圖片大小,調用 GetBitmap() 即可獲得 Bitmap 對象,隨後可保存或流式輸出。JavaScript 動態內容亦可正常渲染截圖。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved