如何拍摄网页的屏幕截图

时间:2015-05-13 06:21:49

标签: c# screenshot

我想截取一个网页的截图。我尝试了很多东西,但它们适用于Windows Forms,我使用的是WebForms和C#。搜索但没有找到。我申请了:

1

private void CaptureMy()
{
    int xheight = 822; int xwidth = 479;
    try
    {
        string StatePath = "Document\\Metro\\Test12.png";
        String filepath = Server.MapPath(StatePath);
        Bitmap captureBitmap = new Bitmap(xheight, xwidth, PixelFormat.Format32bppArgb);
        System.Drawing.Rectangle captureRectangle = Screen.AllScreens[0].Bounds;//capture our Current Screen
        Graphics captureGraphics = Graphics.FromImage(captureBitmap); //Creating a New Graphics Object
        captureGraphics.CopyFromScreen(182, 207, 0, 0, captureRectangle.Size); //Copying Image from The Screen
        ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert(' successfully saved.');", true);
        string Type = Convert.ToString(ViewState["Type"]);
        captureBitmap.Save(filepath, ImageFormat.Jpeg);   //Saving the Image File 
    }
    catch (Exception ex)
    {
    }
}

2

    public void capscreen_test()
    {
        System.Drawing.Image img = FullScreen();
        String path = Server.MapPath("Document/Test13.png");

        string imageFile =  @"\Exceptions\ExceptionLog" + DateTime.Now.ToString("MMddyyyy-hhmmss") + ".jpg";
        img.Save(path);
    }

  public static Bitmap FullScreen()
    {
        return ScreenRectangle(SystemInformation.VirtualScreen);
    }

    public static Bitmap DisplayMonitor(System.Windows.Forms.Screen monitor)
    {
        System.Drawing.Rectangle rect;
        try
        {
            rect = monitor.Bounds;
        }
        catch (Exception ex)
        {
            throw new ArgumentException("Invalid parameter.", "monitor", ex);
        }
        return ScreenRectangle(monitor.Bounds);
    }

    public static Bitmap ActiveWindow()
    {
        IntPtr hwnd;
        Win32.RECT wRect = new Win32.RECT();
        hwnd = Win32.GetForegroundWindow();
        if (hwnd != IntPtr.Zero)
        {
            if (Win32.GetWindowRect(hwnd, ref wRect))
            {
                System.Drawing.Rectangle rect = new System.Drawing.Rectangle(wRect.Left, wRect.Top, wRect.Right - wRect.Left, wRect.Bottom - wRect.Top);
                return ScreenRectangle(rect);
            }
            else
            {
                throw new System.ComponentModel.Win32Exception();
            }
        }
        else
        {
            throw new Exception("Could not find any active window.");
        }
    }

    public static Bitmap Window(IntPtr hwnd)
    {
        Win32.RECT wRect = new Win32.RECT();
        if (hwnd != IntPtr.Zero)
        {
            if (Win32.GetWindowRect(hwnd, ref wRect))
            {
                System.Drawing.Rectangle rect = new System.Drawing.Rectangle(wRect.Left, wRect.Top, wRect.Right - wRect.Left, wRect.Bottom - wRect.Top);
                return ScreenRectangle(rect);
            }
            else
            {
                throw new System.ComponentModel.Win32Exception();
            }
        }
        else
        {
            throw new ArgumentException("Invalid window handle.", "hwnd");
        }
    }

    public static Bitmap Control(Point p)
    {
        IntPtr hwnd;
        Win32.RECT wRect = new Win32.RECT();
        hwnd = Win32.WindowFromPoint(p);
        if (hwnd != IntPtr.Zero)
        {
            if (Win32.GetWindowRect(hwnd, ref wRect))
            {
                System.Drawing.Rectangle rect = new System.Drawing.Rectangle(wRect.Left, wRect.Top, wRect.Right - wRect.Left, wRect.Bottom - wRect.Top);
                return ScreenRectangle(rect);
            }
            else
            {
                throw new System.ComponentModel.Win32Exception();
            }
        }
        else
        {
            throw new Exception("Could not find any window at the specified point.");
        }
    }

    public static Bitmap Control(IntPtr hwnd)
    {
        Win32.RECT wRect = new Win32.RECT();
        if (hwnd != IntPtr.Zero)
        {
            if (Win32.GetWindowRect(hwnd, ref wRect))
            {
                System.Drawing.Rectangle rect = new System.Drawing.Rectangle(wRect.Left, wRect.Top, wRect.Right - wRect.Left, wRect.Bottom - wRect.Top);
                return ScreenRectangle(rect);
            }
            else
            {
                throw new System.ComponentModel.Win32Exception();
            }
        }
        else
        {
            throw new ArgumentException("Invalid control handle.", "hwnd");
        }
    }

    public static Bitmap ScreenRectangle(System.Drawing.Rectangle rect)
    {
        if (!(rect.IsEmpty) && rect.Width != 0 && rect.Height != 0)
        {
            System.ComponentModel.Win32Exception win32Ex = null;
            IntPtr wHdc = Win32.GetDC(IntPtr.Zero);
            if (wHdc == IntPtr.Zero)
            {
                throw new System.ComponentModel.Win32Exception();
            }
            Graphics g;
            Bitmap img = new Bitmap(rect.Width, rect.Height);
            img.MakeTransparent();
            g = Graphics.FromImage(img);
            IntPtr gHdc = g.GetHdc();
            if (!(Win32.BitBlt(gHdc, 0, 0, rect.Width, rect.Height, wHdc, rect.X, rect.Y, Win32.SRCCOPY | Win32.CAPTUREBLT)))
            {
                win32Ex = new System.ComponentModel.Win32Exception();
            }
            g.ReleaseHdc(gHdc);
            g.Dispose();
            Win32.ReleaseDC(IntPtr.Zero, wHdc);
            if (!(win32Ex == null))
            {
                throw win32Ex;
            }
            else
            {
                return img;
            }
        }
        else
        {
            throw new ArgumentException("Invalid parameter.", "rect");
        }
    }
    private class Win32
    {
        public const int CAPTUREBLT = 1073741824;
        public const int BLACKNESS = 66;
        public const int DSTINVERT = 5570569;
        public const int MERGECOPY = 12583114;
        public const int MERGEPAINT = 12255782;
        public const int NOTSRCCOPY = 3342344;
        public const int NOTSRCERASE = 1114278;
        public const int PATCOPY = 15728673;
        public const int PATINVERT = 5898313;
        public const int PATPAINT = 16452105;
        public const int SRCAND = 8913094;
        public const int SRCCOPY = 13369376;
        public const int SRCERASE = 4457256;
        public const int SRCINVERT = 6684742;
        public const int SRCPAINT = 15597702;
        public const int WHITENESS = 16711778;
        public const int HORZRES = 8;
        public const int VERTRES = 10;
        [StructLayout(LayoutKind.Sequential)]
        public struct RECT
        {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;
        }

        [DllImport("user32", SetLastError = true)]
        public static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect);

        [DllImport("user32", SetLastError = true)]
        public static extern int ReleaseDC(IntPtr hWnd, IntPtr hdc);

        [DllImport("user32", SetLastError = true)]
        public static extern IntPtr WindowFromPoint(Point pt);

        [DllImport("user32", SetLastError = true)]
        public static extern IntPtr GetForegroundWindow();

        [DllImport("user32", SetLastError = true)]
        public static extern IntPtr GetDC(IntPtr hwnd);

        [DllImport("gdi32", SetLastError = true)]
        public static extern int GetDeviceCaps(IntPtr hdc, int nIndex);

        [DllImport("gdi32", SetLastError = true)]
        public static extern bool BitBlt(IntPtr hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, uint dwRop);            
    }                                                                       

3

    private void SaveScreenShot()   
    {  
    try
    {
        string StatePath = "Document\\Metro\\error.png";
        String filepath = Server.MapPath(StatePath);
        MemoryStream ms = new MemoryStream();    
       FileStream fs;     
     string fname = Server.MapPath(StatePath);      
    Bitmap bmp = new Bitmap(1280, 1024);//Creating BMP object    
       Graphics gpx = Graphics.FromImage(bmp);//attaching Graphics          
       gpx.CopyFromScreen(0, 0, 0, 0, new Size(1280, 1024));       //Doing Copy from Screen to capture Client Scren     
     bmp.Save(ms, ImageFormat.Gif);       //SAVING the BMP in the Memory stream MS     
     Byte[] buffer = ms.ToArray();       // changing the Memory Stream object to ms   
        ms.Flush();       //flushing the content in ms.   
       ms.Close();       //closing the stream     
     fs = new FileStream(fname, FileMode.Create, FileAccess.ReadWrite);    
       fs.Write(buffer, 0, Convert.ToInt32(buffer.Length));     
      fs.Dispose();       //Writing the Content in ”D://errorimg//error.gif”.  
    } 

    catch {
        Exception ex;
    }
}

这些都不起作用。它们在本地工作正常但不在服务器上工作。请建议我更好地完成任务。

1 个答案:

答案 0 :(得分:0)

我使用过selenium浏览器自动化框架。一个例子:

IWebDriver driver = new InternetExplorerDriver();
driver.Navigate().GoToUrl("http://www.google.com");
Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot();   
ss.SaveAsFile("ss.png", System.Drawing.Imaging.ImageFormat.Png);

通常我会优先使用Firefox或Chrome,但那只是我。