суббота, 23 апреля 2011 г.

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.
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Windows.Forms;
  9. using System.Drawing.Imaging;
  10. using System.Drawing.Drawing2D;
  11. using System.IO;
  12. using System.Runtime.InteropServices;
  13.  
  14. namespace ScreenshotTaker
  15. {
  16.     public partial class Form1 : Form
  17.     {
  18.         public Form1()
  19.         {
  20.             InitializeComponent();
  21.         }
  22.  
  23.         private void btnLoad_Click(object sender, EventArgs e)
  24.         {
  25.             webBrowser1.Navigate("http://www.geekpedia.com");
  26.         }
  27.  
  28.         private void btnSnap_Click(object sender, EventArgs e)
  29.         {
  30.             // The size of the browser window when we want to take the screenshot (and the size of the resulting bitmap)
  31.             Bitmap bitmap = new Bitmap(1024768);
  32.             Rectangle bitmapRect = new Rectangle(001024768);
  33.             // This is a method of the WebBrowser control, and the most important part
  34.             webBrowser1.DrawToBitmap(bitmap, bitmapRect);
  35.  
  36.             // Generate a thumbnail of the screenshot (optional)
  37.             System.Drawing.Image origImage = bitmap;
  38.             System.Drawing.Image origThumbnail = new Bitmap(12090, origImage.PixelFormat);
  39.  
  40.             Graphics oGraphic = Graphics.FromImage(origThumbnail);
  41.             oGraphic.CompositingQuality = CompositingQuality.HighQuality;
  42.             oGraphic.SmoothingMode = SmoothingMode.HighQuality;
  43.             oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
  44.             Rectangle oRectangle = new Rectangle(0012090);
  45.             oGraphic.DrawImage(origImage, oRectangle);
  46.  
  47.             // Save the file in PNG format
  48.             origThumbnail.Save("Screenshot.png", ImageFormat.Png);
  49.             origImage.Dispose();
  50.         }
  51.     }
  52. }

Комментариев нет: