Делаем скриншот веб-страницы программно

Как сделать снимок веб-страницы, программно получив 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();

Но это не работает. Это только дает мне белое пустое изображение. Что мне здесь не хватает?

Есть ли другой способ получить скриншот веб-страницы программно?


person Manish    schedule 23.02.2010    source источник
comment
Этот вопрос был задан только вчера, хотя в основном он касался Perl. Возможно, некоторые из ответов помогут вам, хотя, очевидно, уведут вас в другом направлении. Вот ссылка.   -  person lundmark    schedule 24.02.2010


Ответы (4)


Я искал, искал, искал и нашел эскиз веб-страницы (статья The Code Project).

person Manish    schedule 23.02.2010
comment
Это использует элемент управления веб-браузером Microsoft, который часто дает вам пустой белый снимок экрана. - person jjxtra; 17.07.2012

Отрисовка элемента управления браузера в растровое изображение несколько ненадежно. Я думаю, что было бы лучше просто сделать скриншот вашего окна.

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);
}
person Gabe    schedule 23.02.2010
comment
Этот подход не будет работать в консольном приложении, верно? - person Eugeniu Torica; 20.02.2012

Вы можете попробовать вызвать нативную функцию PrintWindow.

person leppie    schedule 23.02.2010
comment
Можете ли вы объяснить немного больше об этом? Обратите внимание, что у меня есть только URL-адрес веб-страницы в качестве входных данных. - person Manish; 23.02.2010

Вы также можете попробовать P/вызов BitBlt() из gdi32.dll. Попробуйте этот код:

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);
person Simon Linder    schedule 23.02.2010