从WPF的WebBrowser控件保存图像 - 你是如何做到的?

时间:2010-04-29 06:32:31

标签: wpf wpf-controls

大家。可能有一个简单的解决方案,但我似乎找不到一个。我正在使用Visual Studio 2010附带的WPF中的WebBrowser控件,并尝试以编程方式将可能出现在网页上的图像保存到磁盘。

非常感谢提前! 运气

2 个答案:

答案 0 :(得分:6)

添加System.Drawing作为参考,并在应捕获图像的方法中执行以下操作:

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);

答案 1 :(得分:0)

以下是@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);

对于那些喜欢VB方言的人

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)