Taking Website Screenshots With The WebBrowser Control

Taking Website Screenshots With The WebBrowser Control
Sample code on how to take screenshots of websites, resize them to thumbnails and save them as PNG file onto the harddrive.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.IO;
using System.Runtime.InteropServices;
 
namespace ScreenshotTaker
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void btnLoad_Click(object sender, EventArgs e)
        {
            webBrowser1.Navigate("http://www.geekpedia.com");
        }
 
        private void btnSnap_Click(object sender, EventArgs e)
        {
            // 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("Screenshot.png", ImageFormat.Png);
            origImage.Dispose();
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top