Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

To compare two images in C#, first decode them into the same pixel format, confirm that their dimensions and alignment match, then compare corresponding pixels. Use exact equality when any changed pixel matters; use a defined tolerance when small color variations should be ignored. For visual regression work, save a diff image as well as a pass/fail result so you can inspect what changed.

The code below uses System.Drawing for a compact Windows-only example. In .NET 6 and later, System.Drawing.Common is supported only on Windows, so choose another image library if your application must run on macOS or Linux. Microsoft documents that platform restriction.

Choose what “different” means

There is no universal image-comparison rule. The right rule depends on whether you are testing exact file output, checking rendered pages, or trying to ignore insignificant color variation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Method Use it when What it tells you
Exact pixel equality Any pixel change should fail, such as a deterministic image-generation test. Whether every compared pixel has the same channel values.
Per-channel tolerance Small RGB differences should be accepted. Whether every channel difference stays within a limit you set.
Perceptual color distance Visual similarity matters more than identical RGB numbers. Whether corresponding colors differ beyond a perceptual threshold.

A tolerance is a policy decision, not a standard constant. Tune it using representative images from your actual pipeline. Microsoft’s Visual Studio UI testing API includes comparison overloads with color-difference tolerance and tolerance rectangles; the ImageDiff project documents both an ExactMatch mode and a CIE76 mode. Microsoft ImageComparer API · ImageDiff project

#1 Best Overall
Sale
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
  • WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
  • A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents

Use exact pixel comparison in C#

This example compares decoded bitmaps pixel by pixel, reports the number of mismatching pixels, and writes a diff image. Changed pixels are highlighted in magenta; matching pixels are dimmed to make the differences easier to see.

Create a console project targeting Windows, then add the drawing package if your target framework requires it:

dotnet new console -n ImageCompare
cd ImageCompare
dotnet add package System.Drawing.Common

Replace Program.cs with the following. Supply two image paths as command-line arguments, for example dotnet run -- expected.png actual.png.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
using System;
using System.Drawing;
using System.Drawing.Imaging;

if (args.Length < 2)
{
    Console.Error.WriteLine("Usage: ImageCompare <expected-image> <actual-image> [diff-image]");
    return 2;
}

string expectedPath = args[0];
string actualPath = args[1];
string diffPath = args.Length > 2 ? args[2] : "diff.png";

using var expected = new Bitmap(expectedPath);
using var actual = new Bitmap(actualPath);

if (expected.Width != actual.Width || expected.Height != actual.Height)
{
    Console.Error.WriteLine($"Dimensions differ: expected {expected.Width}x{expected.Height}, " +
                            $"actual {actual.Width}x{actual.Height}.");
    return 1;
}

using var diff = new Bitmap(expected.Width, expected.Height, PixelFormat.Format32bppArgb);
long differingPixels = 0;

for (int y = 0; y < expected.Height; y++)
{
    for (int x = 0; x < expected.Width; x++)
    {
        Color a = expected.GetPixel(x, y);
        Color b = actual.GetPixel(x, y);
        bool differs = a.ToArgb() != b.ToArgb();

        if (differs)
        {
            differingPixels++;
            diff.SetPixel(x, y, Color.Magenta);
        }
        else
        {
            // Keep unchanged areas visible but subdued.
            int gray = (a.R + a.G + a.B) / 3;
            diff.SetPixel(x, y, Color.FromArgb(255, gray / 3, gray / 3, gray / 3));
        }
    }
}

diff.Save(diffPath, ImageFormat.Png);
Console.WriteLine($"Different pixels: {differingPixels} of {(long)expected.Width * expected.Height}");
Console.WriteLine($"Diff image: {diffPath}");
return differingPixels == 0 ? 0 : 1;

The program returns exit code 0 when images match and 1 when they differ or their dimensions do not match; invalid invocation returns 2. This makes it usable in a basic test or automation step. The diff image has the same dimensions as the inputs, with changed coordinates marked magenta.

Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
  • SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors

Why dimensions and format matter

This implementation rejects unequal dimensions rather than silently cropping or scaling. Cropping can hide added content; scaling can shift edges and create differences that were not present in the source. If the inputs are expected to have different sizes, define an intentional normalization rule before comparison.

The code decodes both images through Bitmap and compares ARGB values returned by GetPixel. This is a straightforward teaching approach, not a performance claim: the reviewed sources do not establish that repeated GetPixel calls are suitable for high-throughput production workloads. If speed matters, benchmark a library and pixel-access strategy against your image sizes and deployment runtime.

Add a per-channel tolerance

If minor channel changes should be ignored, replace the exact comparison line with a rule such as this:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
static bool WithinTolerance(Color a, Color b, int tolerance)
{
    return Math.Abs(a.R - b.R) <= tolerance
        && Math.Abs(a.G - b.G) <= tolerance
        && Math.Abs(a.B - b.B) <= tolerance
        && Math.Abs(a.A - b.A) <= tolerance;
}

Then use bool differs = !WithinTolerance(a, b, tolerance); in the loop and define tolerance as an application setting between 0 and 255. A tolerance of zero is exact equality. With this rule, each channel must independently stay within the limit; it does not cap a combined RGB distance. Decide explicitly whether alpha should be compared—transparent pixels can carry different RGB values even when they render similarly.

Rank #3
Sale
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
  • Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
  • Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
  • In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
  • Ultra-thin bezels: Maximize your viewing experience with thin bezels.

For comparison closer to perceived color difference, compare colors in a perceptual space such as CIE L*a*b* and mark a pixel when its color distance exceeds a selected threshold. A Mescius C# demo illustrates this approach and renders differing pixels in magenta over subdued grayscale. Its sample threshold is a demo choice, not a general-purpose value. Mescius image-comparison demo

Account for alignment and dynamic regions

Pixel comparison assumes that coordinate (x, y) in one image corresponds to the same content at (x, y) in the other. A one-pixel shift can make a large area appear different even when the underlying page or object is otherwise unchanged. Before interpreting a diff, ensure the captures use the same crop, orientation, dimensions, viewport, and rendering conditions. The sources cited here do not provide a complete image-registration algorithm; if inputs are not aligned, resolve that separately rather than treating a raw pixel diff as a visual-similarity judgment.

For screenshots, also consider whether changing timestamps, rotating content, animation, or personalized areas should count as failures. Microsoft’s ImageComparer includes overloads for tolerance rectangles, which can help exclude or specially handle known regions when that API fits your project. Avoid ignoring large areas without a clear reason: a broad mask can conceal a real regression.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Other C# comparison options

Microsoft Visual Studio UI testing ImageComparer

ImageComparer.Compare accepts actual and expected System.Drawing.Image values. The documented API includes boolean comparison, color-difference tolerance, tolerance rectangles, and overloads that return a difference image. The documentation page is for the Visual Studio SDK 2017 view; confirm package and API availability for your target project rather than assuming it is part of every .NET installation. ImageComparer API reference

Rank #4
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
  • SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
  • MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
  • KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
  • INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient

ImageDiff

The third-party ImageDiff project describes a workflow that analyzes images, detects and labels differences, and builds bounding boxes around them. Its documented choices include ExactMatch and CIE76 analyzers, padding controls, basic or connected-component labeling, and single or multiple bounding-box modes. Check its current maintenance status and compatibility with your framework before adopting it; those points are not established by the cited project summary. ImageDiff project

ScreenshotNeo for comparing live-page captures

If your inputs are screenshots of web pages rather than local image files, ScreenshotNeo can capture pages as PNG, JPEG, WebP, or PDF; it is not itself a pixel-diff algorithm. Capture comparable pages with matching settings, then feed the resulting images into the comparison method you choose.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

For a screenshot input, one GET request returns the capture. See the ScreenshotNeo API documentation for request options and response details.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

ScreenshotNeo accepts the cookie or consent banner like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each of those steps can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000. These are the stated plan allowances and prices; check the site for current availability.

Sign up for ScreenshotNeo’s free plan to get 1,000 screenshots a month with no card.

Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
  • 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
  • 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.

Troubleshooting common comparison problems

  • Build fails or runtime reports an unsupported platform: System.Drawing.Common is Windows-only in .NET 6 and later. Run this example on Windows or use a library compatible with your target operating systems.
  • Every pixel differs after a seemingly small change: Check image dimensions, crop, orientation, and alignment first. Then confirm whether the chosen rule is exact equality or tolerance-aware.
  • Transparent images produce surprising differences: Decide whether alpha belongs in the comparison and whether transparent pixels should be composited against a consistent background before comparison.
  • The diff image is missing or cannot be opened: Verify the output directory is writable and that the program reached the save operation. Use a PNG path for the example’s ImageFormat.Png output.
  • The comparison is too slow for a large batch: The example favors clarity over an established throughput claim. Profile with representative files and evaluate bulk pixel access or a library designed for image processing before scaling up.
  • Web screenshots vary between runs: Standardize viewport and capture conditions, and decide whether dynamic regions should be masked. A pixel diff reports coordinate-level changes; it does not determine whether a page is semantically equivalent.

Choose a method for your project

Use the simplest rule that matches the failure you care about. Exact equality is easy to explain and produces an unambiguous result, but it will flag any encoded pixel change. A channel tolerance can reduce sensitivity to small variations, while perceptual color distance changes the meaning of “close enough.” For visual regression, pair whichever rule you choose with an inspectable diff and a deliberate policy for dimensions, alignment, and dynamic regions.

Before adding a dependency, verify its target framework and operating-system support. Microsoft’s general .NET guidance emphasizes matching image-processing choices to project constraints and balancing performance with output quality; it does not supply a universal speed ranking for the approaches above. Microsoft .NET image-processing guidance

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Does this C# example work on Linux or macOS?

No. It uses System.Drawing.Common, which Microsoft supports only on Windows in .NET 6 and later. Use an image library that supports your deployment platforms.

Can a tolerance hide real changes?

Yes. Any nonzero threshold can accept differences, so choose and validate it against representative images and the changes your application must catch.

Does ScreenshotNeo compare images?

No. It captures web pages; use a separate image-comparison implementation to analyze its output.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.