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

和自甴很熟 提交于 2019-12-06 14:09:32

问题


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. With no such luck have I found any in 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!!!


回答1:


Some of the objects you're creating are IDisposable. You need to make sure Dispose() gets called on them. 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.



来源:https://stackoverflow.com/questions/25670634/are-there-any-good-examples-of-how-to-take-a-screenshot-in-selenium-webdriver-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!