简体   繁体   English

有没有很好的示例,说明如何使用Selenium Webdriver C#截屏,然后裁剪并保存图像?

[英]Are there any good examples of how to take a screenshot in selenium webdriver C#, then crop and save the image?

I've been searching for some good examples of how to take a screenshot using ITakesScreenshot in Selenium Webdriver in C#, then to crop the image using the elements dimensions and then saving this new image. 我一直在寻找一些很好的示例,这些示例如何使用C#的Selenium Webdriver中的ITakesScreenshot截屏,然后使用元素尺寸裁剪图像,然后保存此新图像。 With no such luck have I found any in C#. 运气不好,我在C#中找不到任何东西。

I have this method at the moment but every so often I get a Out of Memory exception when used in a test. 目前,我有此方法,但是在测试中使用时,经常会遇到内存不足异常。 It fails on the line where it tries to crop. 它在尝试裁剪的线上失败。

public void TakeScreenShotOfElement(IWebDriver _driver, string rootpath, string imgName, string element2)
    {

            string element3 = element2;
            var element = driver.FindElement(By.XPath(element3));
            Byte[] ba = ((ITakesScreenshot)driver).GetScreenshot().AsByteArray;
            var ss = new Bitmap(new MemoryStream(ba));

            var crop = new Rectangle(element.Location.X, element.Location.Y, element.Size.Width, element.Size.Height);

            //create a new image by cropping the original screenshot
            Bitmap image2 = ss.Clone(crop, ss.PixelFormat);


            if (!Directory.Exists(rootpath))
            {
                Directory.CreateDirectory(rootpath);
            }
            image2.Save(String.Format("{0}\\{1}.png", rootpath, imgName), System.Drawing.Imaging.ImageFormat.Png);

    }

Any help is much appreciated, thanks in advance!!! 非常感谢任何帮助,在此先感谢!!!

Some of the objects you're creating are IDisposable . 您正在创建的某些对象是IDisposable You need to make sure Dispose() gets called on them. 您需要确保在它们上调用了Dispose() As it stands they're not releasing the memory they've claimed, which is why you get the exceptions. 就目前而言,他们没有释放他们声称的内存,这就是为什么您会获得例外的原因。

The easiest way to make sure these items get disposed is to wrap each of them in a using block. 确保处理这些项目的最简单方法是将它们包装在using块中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM