Search code examples
c#seleniumwebdrivercrop

C# Cropping image return wrong coordinates


I've been trying to crop a specific image using Selenium and different cropping methods for a few days.

An important note before my code - the following method used to work 2 weeks ago and for some reason it now returns an image with wrong coordinates

// Go to site
Driver.Navigate().GoToUrl("http://google.com");
Screenshot screenshot = driver.GetScreenshot();

using (var ms = new MemoryStream(screenshot.AsByteArray))
using (var imgShot = Image.FromStream(ms))
using (var src = new Bitmap(imgShot))
      {
        IWebElement element = driver.FindElement(By.XPath("//canvas"));
        Rectangle cropRect = new Rectangle(element.Location.X, element.Location.Y, element.Size.Width, element.Size.Height);

        var clone = src.Clone(cropRect, src.PixelFormat);
        clone.Save(filePath);
      }

Things I tried:

1) I usually use Firefox driver for this purpose, I tried using ChromeDriver instead and got the same result.

2) I checked for the element's coordiantes using the following console command: $0.getBoundingClientRect() and the position I got in my code matches it.

3) I tried 4 different cropping methods including this one:

IWebElement element = Driver.FindElement(By.XPath("//canvas"));
string filename = @"C:\Users\User\Desktop\test.png";
Screenshot screenshot = Driver.GetScreenshot();
screenshot.SaveAsFile(filename, ImageFormat.Png);

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

using (Image imgShot = Image.FromFile(filename))
using (Bitmap original = new Bitmap(imgShot))
using (Bitmap target = new Bitmap(original, new Size(cropRect.Width, cropRect.Height)))
using (Graphics g = Graphics.FromImage(target))
{
    g.DrawImage(original, new Rectangle(0, 0, target.Width, target.Height),
        cropRect,
        GraphicsUnit.Pixel);
    target.Save(@"C:\Users\User\Desktop\test1.png", ImageFormat.Png);
}

Just to be clear, the image I get is totally blank. In a different website the image I get is not blank so I can tell it's just in the wrong coordinates.

4) I tried a different website and different elements and they were all in the wrong coordinates.

5) I tried to Google it and found so many different approaches that didn't work. This answer however, says something about resolution which was my best guess. I tried playing with both the original and the target's resolution and saw no difference. The set resolution method was called either before or after the Graphics variable was created and still, zero change.

The funny thing is, it used to work 2 weeks ago but I never changed the code...


Solution

  • So apparently the thing that actually changed 2 weeks ago wasn't my code but the Firefox version installed on my machine. The current version - v52, return elements in wrong coordinates. Uninstalling it and reinstalling the previous version - v47 solved the issue