Image comparison in Selenium WebDriver using Java

aarsha picture aarsha · Mar 15, 2016 · Viewed 8.6k times · Source

I am currently working in Selenium WebDriver to compare two images during automation. Currently I am using pixel comparison but the problem comes if the browser size is changed or the system is different on which I run the automation.

I have to compare two images, one is the golden one which is already saved in a location and the other one is the screenshot taken during the automation. As soon as the screenshot is taken, it is compared with the golden image I have, and a pass or fail is asserted accordingly. The problem comes if the browser size or the system resolution is different when the screenshot is taken, because this will affect the resolution of the image which might not be same as the resolution of the golden image I have for reference. Here both the images are same but the pixels might change with the browser size or system change.

So is there any way to compare two images using java in selenium with out using pixel comparison?

Answer

Leszek_PL picture Leszek_PL · Sep 12, 2018

The key thing here is the resolution, you must ensure that resolution is the same for base "golden" images and those you capture during test.

  1. Set size of the browser window to fixed size, eg. (1920x1080),
  2. Make all screenshots in this resolution,
  3. During the test: before each image-comparison check if the window size is (1920x1080) if not I change it temporarily,
  4. Take screenshot,
  5. Compare image with original "golden" img
  6. Do window maximize

Other solution is to capture screenshots of single WebElement rather than whole page, because WebElements often are resolution independent.