Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving an Image from WPF's WebBrowser control - how do you do it?

everyone. There's probably a simple solution to this but I can't seem to find one. I'm playing around with the WebBrowser control in WPF that ships with Visual Studio 2010 and am trying to save an image that might appear on a webpage to disk programmatically.

Many thanks in advance! Luck

like image 694
Luck Avatar asked Apr 29 '10 06:04

Luck


2 Answers

Add System.Drawing as reference and perform the following oprations in the method that should capture the image:

Rect bounds = VisualTreeHelper.GetDescendantBounds(browser1);

System.Windows.Point p0 = browser1.PointToScreen(bounds.TopLeft);
System.Drawing.Point p1 = new System.Drawing.Point((int)p0.X, (int)p0.Y);

Bitmap image = new Bitmap((int)bounds.Width, (int)bounds.Height);
Graphics imgGraphics = Graphics.FromImage(image);

imgGraphics.CopyFromScreen(p1.X, p1.Y,
                           0, 0,
                           new System.Drawing.Size((int)bounds.Width,
                                                        (int)bounds.Height));

image.Save("C:\\a.bmp", ImageFormat.Bmp);
like image 194
luvieere Avatar answered Nov 06 '22 22:11

luvieere


Here are the adaptions to solution of @luvieere:

WebBrowser browser1;
browser1 = this.Browser;

// I used the GetContentBounds()
Rect bounds = VisualTreeHelper.GetContentBounds(browser1);
// and the point to screen command for the top-left and the bottom-right corner
System.Windows.Point pTL = browser1.PointToScreen(bounds.TopLeft);
System.Windows.Point pBR = browser1.PointToScreen(bounds.BottomRight);

System.Drawing.Bitmap image = new 
// The size is then calculated as difference of the two corners
System.Drawing.Bitmap(
    System.Convert.ToInt32(pBR.X - pTL.X),   
    System.Convert.ToInt32(pBR.Y - pTL.Y));

System.Drawing.Graphics imgGraphics = System.Drawing.Graphics.FromImage(image);

imgGraphics.CopyFromScreen(pTL.X, pTL.Y, 0, 0, new System.Drawing.Size(image.Width, image.Height));

fileName = System.IO.Path.GetFileNameWithoutExtension(fileName) + ".bmp";
image.Save(fileName, System.Drawing.Imaging.ImageFormat.Bmp);

For those, who prefer VB-dialect

Dim browser1 As WebBrowser
browser1 = Me.Browser

Dim bounds As Rect = VisualTreeHelper.GetContentBounds(browser1)

Dim pTL As System.Windows.Point = browser1.PointToScreen(bounds.TopLeft)
Dim pBR As System.Windows.Point = browser1.PointToScreen(bounds.BottomRight)

Dim image As System.Drawing.Bitmap = New System.Drawing.Bitmap(CInt(pBR.X - pTL.X), CInt(pBR.Y - pTL.Y))
Dim imgGraphics As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(image)

imgGraphics.CopyFromScreen(pTL.X, pTL.Y, 0, 0, New System.Drawing.Size(image.Width, image.Height))

fileName = IO.Path.GetFileNameWithoutExtension(fileName) & ".bmp"
image.Save(fileName, System.Drawing.Imaging.ImageFormat.Bmp)
like image 44
DrMarbuse Avatar answered Nov 06 '22 22:11

DrMarbuse