需對指定網頁進行截圖並生成指定尺寸縮略圖。本文提供核心類 GetImage 與內部類 WebPageBitmap,基於 WebBrowser 控件實現 1:1 截圖與高質量縮放。
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 動態內容亦可正常渲染截圖。