【问题标题】:Taking screenshot of a webpage programmatically [closed]以编程方式截取网页截图[关闭]
【发布时间】:2010-02-23 08:03:58
【问题描述】:

如果输入 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。也许那里的一些答案会对您有所帮助,尽管显然会带您进入另一个方向。这是link

标签: c# .net screenshot webpage-screenshot


【解决方案1】:

我搜了又搜,终于找到了Webpage thumbnailer(一篇The Code Project的文章)。

【讨论】:

  • 这使用了微软的网络浏览器控件,经常给你一个空白的截图
【解决方案2】:

将浏览器控件绘制为位图有点不可靠。我认为最好只截屏你的窗口。

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】:

你可以尝试调用原生的PrintWindow函数。

【讨论】:

  • 你能解释一下吗?请注意,我只输入了网页的 URL。
【解决方案4】:

您也可以尝试从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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-02
    • 2015-02-23
    • 1970-01-01
    • 1970-01-01
    • 2014-04-17
    • 2010-12-16
    • 1970-01-01
    相关资源
    最近更新 更多