从WPF的WebBrowser控件保存图像-您是怎么做的?

问题描述 投票:5回答:2

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

非常感谢!运气

wpf wpf-controls
2个回答
7
投票

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

0
投票

这里是@luvieere作为VB.NET代码的解决方案

Private Function saveBrowserImage(Optional fileName As String = Nothing) As String

    If fileName Is Nothing Then
        fileName = IO.Path.GetTempFileName
    End If

    Try
        Dim browser1 As WebBrowser
        browser1 = Me.Browser

        Dim bounds As Rect = VisualTreeHelper.GetDescendantBounds(browser1)
        Dim p0 As System.Windows.Point = browser1.PointToScreen(bounds.TopLeft)
        Dim p1 As System.Drawing.Point = New System.Drawing.Point(CInt(p0.X), CInt(p0.Y))
        Dim image As System.Drawing.Bitmap = New System.Drawing.Bitmap(CInt(bounds.Width), CInt(bounds.Height))
        Dim imgGraphics As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(image)

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

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

        Return fileName
    Catch ex As Exception
        Return Nothing
    End Try
End Function
© www.soinside.com 2019 - 2024. All rights reserved.