像WPF中的图像一样捕获网页的一部分?

时间:2012-02-16 17:41:59

标签: .net wpf xaml webpage

我只是想知道是否有可能以某种方式捕获WPF中的图像部分网页

谢谢!

2 个答案:

答案 0 :(得分:2)

对于WinForms,我做了你想要的事情。 Here is the code snippet。我想,你也可以用同样的方式用WPF轻松完成。

基本上将网站捕获为截图并将其保存到图像是一种常规操作。目前它只适用于页面适合一个屏幕,它不能滚动或做其他花哨的东西。

答案 1 :(得分:0)

首先感谢@Uwe Keim !!!!

所以我使用他的代码来做我需要的:捕获和裁剪WebBrowser控件的任何部分。

  1. 代码本身(它应该像DLL一样实现。)
  2. 命名空间测试 {

    使用System;

    使用System.Diagnostics;

        using System.Drawing;
        using System.Drawing.Drawing2D;
        using System.Drawing.Imaging;
        using System.IO;
        using System.Runtime.InteropServices;
        using System.Windows.Forms;
    
    
    public class WebBrowserScreenshotCapture
    {
        private class FocuslessForm : Form { }
    
        public void CaptureBrowserScreenshot(Uri url, FileInfo saveAsFilePath, Point scrollTo, Rectangle cropToRectangle)
        {
            var sb = Math.Max(SystemInformation.VerticalScrollBarWidth,SystemInformation.HorizontalScrollBarHeight);
    
            var size = new Size(Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height);
    
            using (var form =
                new FocuslessForm
                {
                    Width = size.Width + sb,
                    Height = size.Height + sb,
                    Padding = new Padding(0),
                    Margin = new Padding(0),
                    FormBorderStyle = FormBorderStyle.None,
                    Opacity = 0,
                    TabStop = false,
                    ShowInTaskbar = false
                })
            {
                var webBrowser1 =   new WebBrowser
                    {
                        Padding = new Padding(0),
                        Margin = new Padding(0),
                        Dock = DockStyle.Fill,
                        Url = url,
                        TabStop = false
                    };
                form.Controls.Add(webBrowser1);
    
                var finished = false;
    
                webBrowser1.DocumentCompleted += delegate { webBrowser1.Document.Window.ScrollTo(scrollTo); finished = true; };
    
                form.Show();
    
                while (!finished)
                {
                    Application.DoEvents();
                }
    
                CaptureBrowserScreenshot(webBrowser1, saveAsFilePath, cropToRectangle);
                form.Close();
            }
        }
    
        public void CaptureBrowserScreenshot(WebBrowser webBrowser, FileInfo saveAsFilePath,  Rectangle cropToRectangle)
        {
            using (var screenshot = new Bitmap(webBrowser.ClientSize.Width,  webBrowser.ClientSize.Height))
            {
                getImage(webBrowser.ActiveXInstance, screenshot, Color.White);
    
                using (var effectiveImage = new Bitmap(webBrowser.ClientSize.Width - SystemInformation.VerticalScrollBarWidth, webBrowser.ClientSize.Height - SystemInformation.HorizontalScrollBarHeight))
                {
                    using (var graphics = Graphics.FromImage(effectiveImage))
                    {
                        graphics.DrawImageUnscaled(screenshot, 0, 0);
                    }
    
                    using (var croppedImage = cropImage(effectiveImage, cropToRectangle))
                    {
                        croppedImage.Save(saveAsFilePath.FullName, getImageFormatFromFileExtension(saveAsFilePath.Extension));
                    }   
                }
            }
        }       
    
        private static Image cropImage(Bitmap image, Rectangle cropRect)
        {
            var effectiveImage = new Bitmap(cropRect.Width,cropRect.Height);
    
            using (var graphics = Graphics.FromImage(effectiveImage))
            {
                graphics.DrawImage(image, 0, 0, cropRect, GraphicsUnit.Pixel);
            }
    
            return effectiveImage;
        }    
    
        private static bool needReduceSizeProportionally(Image image,int maxWidth,  int maxHeight)
        {
            if (image == null)
            {
                return false;
            }
            else
            {
                if (image.Width <= maxWidth && image.Height <= maxHeight)
                {
                    // Nothing to do.
                    return false;
                }
                else
                {
                    return true;
                }
            }
        }
    
        private static ImageFormat getImageFormatFromFileExtension(string extension)
        {
            extension = extension.Trim('.').ToLowerInvariant();
    
            ImageFormat format;
            switch (extension)
            {
                case @"bmp":
                    format = ImageFormat.Bmp;
                    break;
    
                case @"png":
                    format = ImageFormat.Png;
                    break;
    
                case @"gif":
                    format = ImageFormat.Gif;
                    break;
    
                case @"jpg":
                case @"jpeg":
                    format = ImageFormat.Jpeg;
                    break;
    
                case @"tif":
                case @"tiff":
                    format = ImageFormat.Tiff;
                    break;
    
                default:
                    Trace.WriteLine(
                        string.Format(
                            @"Unknown file format extension '{0}'. Using PNG instead.",
                            extension));
                    format = ImageFormat.Png;
                    break;
            }
    
            return format;
        }
    
        [ComImport]
        [Guid(@"0000010D-0000-0000-C000-000000000046")]
        [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        private interface IViewObject
        {
            void Draw([MarshalAs(UnmanagedType.U4)] uint dwAspect, int lindex, IntPtr pvAspect, [In] IntPtr ptd, IntPtr hdcTargetDev, IntPtr hdcDraw, [MarshalAs(UnmanagedType.Struct)] ref RECT lprcBounds, [In] IntPtr lprcWBounds, IntPtr pfnContinue, [MarshalAs(UnmanagedType.U4)] uint dwContinue);
        }
    
        [StructLayout(LayoutKind.Sequential, Pack = 4)]
        private struct RECT
        {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;
        }
    
        private static void getImage(object obj, Image destination, Color backgroundColor)
        {
            using (var graphics = Graphics.FromImage(destination))
            {
                var deviceContextHandle = IntPtr.Zero;
                var rectangle = new RECT { Right = destination.Width, Bottom = destination.Height };
    
                graphics.Clear(backgroundColor);
    
                try
                {
                    deviceContextHandle = graphics.GetHdc();
    
                    var viewObject = (IViewObject)obj;
                    viewObject.Draw(1, -1, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, deviceContextHandle, ref rectangle, IntPtr.Zero, IntPtr.Zero, 0);
                }
                finally
                {
                    if (deviceContextHandle != IntPtr.Zero)
                    {
                        graphics.ReleaseHdc(deviceContextHandle);
                    }
                }
            }
        }
    }
    

    }

    1. 如何使用它。

      WebBrowserScreenshotCapture c = new WebBrowserScreenshotCapture();

      Point scrollWebpageTo = new Point(0,300);

      c.CaptureBrowserScreenshot(新的Uri(“http://website.com”),新的System.IO.FileInfo(@“D:\ test.png”),scrollWebpageTo,new Rectangle(400,300,200,300));