以编程方式截取网页屏幕截图

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();

但这并不起作用,它只给了我一张空白图片。我在这里缺少什么?

还有其他什么方法可以通过编程方式获取网页截图吗?


这个问题昨天刚被问到,虽然主要是针对Perl的。也许那里的一些答案可以帮助你,但显然会让你走向另一个方向。这是链接:https://dev59.com/oHE95IYBdhLWcg3wbtbO。 - lundmark
4个回答

7

2
这使用了微软的Web浏览器控件,经常会给你一个空白的白色截图。 - jjxtra

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), 
        bitmap.Size);
        bitmap.Save(filename);
}

3
这种方法在控制台应用程序中行不通,对吗? - Eugeniu Torica

2
您可以尝试调用本地的PrintWindow函数。

1
你能再详细解释一下吗?请注意,我只有网页的URL作为输入。 - Manish

0
您也可以尝试从“gdi32.dll”中使用P/Invoke调用“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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接