'Take a screenshot and compare it with another image using playwright.net - C#

I m trying to take a screenshot of a section on the page and compare it with another image already saved using playwright and .NET. I managed to take the screenshot but i cant do the comparison. On playwright site, they show how to do it using javascript but there is no equivalent in .Net. can anyone please advise how to make the code below works in .NET. Thank you

expect(await.Locator(".layer").ScreenshotAsync.toMatchSnapshot('home.png', { threshold: 0.2 });


Solution 1:[1]

You can use ImageSharpCompare for this.

Here's how I do it. This is using MSTest, so replace Assert.IsEqual with whatever your runner uses.

  <ItemGroup>
    <PackageReference Include="Codeuctivity.ImageSharpCompare" Version="2.0.25" />
    <PackageReference Include="SixLabors.ImageSharp" Version="2.1.0" />
  </ItemGroup>
using Codeuctivity.ImageSharpCompare;
using SixLabors.ImageSharp;

var bytes = await Page.ScreenshotAsync();
using var actual = Image.Load(bytes);
using var expected = Image.Load(expected_filename);
Assert.IsTrue(ImageSharpCompare.ImagesAreEqual(actual,expected),expected_filename);

ImageSharpCompare also has options for reducing how precisely equal the images need to be in order to pass.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 James Coliz