2010-02-23 51 views
15

如何以編程方式將URL作爲輸入來捕捉網頁的屏幕?以編程方式對網頁進行截圖

這裏是我到現在爲止:

// The size of the browser window when we want to take the screenshot (and the size of the resulting bitmap) 
Bitmap bitmap = new Bitmap(1024, 768); 
Rectangle bitmapRect = new Rectangle(0, 0, 1024, 768); 
// This is a method of the WebBrowser control, and the most important part 
webBrowser1.DrawToBitmap(bitmap, bitmapRect); 

// Generate a thumbnail of the screenshot (optional) 
System.Drawing.Image origImage = bitmap; 
System.Drawing.Image origThumbnail = new Bitmap(120, 90, origImage.PixelFormat); 

Graphics oGraphic = Graphics.FromImage(origThumbnail); 
oGraphic.CompositingQuality = CompositingQuality.HighQuality; 
oGraphic.SmoothingMode = SmoothingMode.HighQuality; 
oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic; 
Rectangle oRectangle = new Rectangle(0, 0, 120, 90); 
oGraphic.DrawImage(origImage, oRectangle); 

// Save the file in PNG format 
origThumbnail.Save(@"d:\Screenshot.png", ImageFormat.Png); 
origImage.Dispose(); 

但是,這是行不通的。它只給我一張白色的空白圖片。我在這裏錯過了什麼?

是否有任何其他方式我可以以編程方式獲取網頁的屏幕截圖?

+0

昨天剛剛問了這個問題,雖然主要針對Perl。也許一些答案會幫助你,雖然顯然會帶你另一個方向。這裏是[鏈接](http://stackoverflow.com/questions/2312852/how-can-i-take-screenshots-with-perl)。 – lundmark 2010-02-23 21:49:54

回答

2

您可以嘗試調用本地PrintWindow函數。

+1

你能解釋一下嗎?請注意,我只是將網頁的網址作爲輸入。 – Manish 2010-02-23 09:11:54

3

將瀏覽器控件繪製爲位圖有點不可靠。我認爲只是在屏幕上擦窗戶會更好。

using (Bitmap bitmap = new Bitmap(bitmapSize.Width, bitmapSize.Height, PixelFormat.Format24bppRgb)) 
using (Graphics graphics = Graphics.FromImage(bitmap)) 
{ 
    graphics.CopyFromScreen(
     PointToScreen(webBrowser1.Location), 
     new Point(0, 0), 
     bitmapSize); 
     bitmap.Save(filename); 
} 
+3

這種方法在控制檯應用程序中不起作用,對吧? – 2012-02-20 13:04:51

0

您也可以嘗試P /從gdi32.dll調用BitBlt()。試試這個代碼:

Graphics mygraphics = webBrowser1.CreateGraphics(); 
Size s = new Size(1024, 768); 
Bitmap memoryImage = new Bitmap(s.Width, s.Height, mygraphics); 
Graphics memoryGraphics = Graphics.FromImage(memoryImage); 
IntPtr dc1 = mygraphics.GetHdc(); 
IntPtr dc2 = memoryGraphics.GetHdc(); 
// P/Invoke call here 
BitBlt(dc2, 0, 0, webBrowser1.ClientRectangle.Width, webBrowser1.ClientRectangle.Height, dc1, 0, 0, 13369376); 
mygraphics.ReleaseHdc(dc1); 
memoryGraphics.ReleaseHdc(dc2); 
memoryImage.Save(filename); 

的的P/Invoke將是:

[DllImport("gdi32.dll")] 
[return: MarshalAs(UnmanagedType.Bool)] 
internal static extern bool BitBlt(IntPtr hdc, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, uint dwRop);