Getting a screenshot of a page using .NET - Need help with code
- by Ender
I'm writing a specialized crawler and parser for internal use and I require the ability to take a screenshot of a web page in order to check what colours are being used throughout. The program will take in around ten web addresses and will save them as a bitmap image, from there I plan to use LockBits in order to create a list of the five most used colours within the image. To my knowledge it's the easiest way to get the colours used within a web page but if there is an easier way to do it please chime in with your suggestions.
Anyway, I was going to use this program until I saw the price tag. I'm also fairly new to C#, having only used it for a few months. Can anyone provide me with a solution to my problem of taking a screenshot of a web page in order to extract the colour scheme?
EDIT: Sorry for not getting back to this sooner, but I've been busy with some other things. Anyway, the code seems to work well, but the problem I am having right now is that I am running it within a form, and naturally with Application.Run() being called I cannot run two instances of the same form at once. It recommended Form.showDialog() but that broke everything. Can anyone give me a hand with this code?
public static void buildScreenshotFromURL(string url) {
int width = 800;
int height = 600;
using (WebBrowser browser = new WebBrowser()) {
browser.Width = width;
browser.Height = height;
browser.ScrollBarsEnabled = true;
// This will be called when the page finishes loading
browser.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(OnDocumentCompleted);
//browser.DocumentCompleted += OnDocumentCompleted;
browser.Navigate(url);
// This prevents the application from exiting until
// Application.Exit is called
// Application.Run() does not work as it cannot be called twice, recommended form.showDialog()
// but still issues
Application.Run();
}
}
public static void OnDocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {
// Define size of thumbnail neded
int thumbSize = 50;
// Now that the page is loaded, save it to a bitmap
WebBrowser browser = (WebBrowser)sender;
// Code edited from example below to make smaller bitmap and save as PNG
using (Graphics graphics = browser.CreateGraphics()) {
using (Bitmap bitmap = new Bitmap(browser.Width, browser.Height, graphics)) {
Rectangle bounds = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
browser.DrawToBitmap(bitmap, bounds);
Bitmap thumbBitmap = new Bitmap(bitmap.GetThumbnailImage(thumbSize, thumbSize, thumbCall, IntPtr.Zero));
thumbBitmap.Save("screenshot.png", ImageFormat.Png);
handleImage(thumbBitmap);
}
}