Title: Compare images to find differences in C#
This example lets you compare images to see if they are the same. When you select two images to compare and click the Go button, the program executes the following code to compare the images and see at which pixels they differ.
private void btnGo_Click(object sender, EventArgs e)
this.Cursor = Cursors.WaitCursor;
// Load the images.
Bitmap bm1 = (Bitmap)picImage1.Image;
Bitmap bm2 = (Bitmap)picImage2.Image;
// Make a difference image.
int wid = Math.Min(bm1.Width, bm2.Width);
int hgt = Math.Min(bm1.Height, bm2.Height);
Bitmap bm3 = new Bitmap(wid, hgt);
// Create the difference image.
bool are_identical = true;
Color eq_color = Color.White;
Color ne_color = Color.Red;
for (int x = 0; x < wid; x++)
for (int y = 0; y < hgt; y++)
if (bm1.GetPixel(x, y).Equals(bm2.GetPixel(x, y)))
bm3.SetPixel(x, y, eq_color);
bm3.SetPixel(x, y, ne_color);
are_identical = false;
// Display the result.
picResult.Image = bm3;
this.Cursor = Cursors.Default;
if ((bm1.Width != bm2.Width) || (bm1.Height != bm2.Height)) are_identical = false;
lblResult.Text = "The images are identical";
lblResult.Text = "The images are different";
The code loads the two image files into Bitmaps. It finds the smaller of the Bitmaps' widths and heights, and makes a new Bitmap of that size.
Next the program loops over the pixels in the smaller area, comparing the images' pixels. If two corresponding pixels are equal, the program colors the result pixel white. If the two pixels are different, the program makes the result pixel red. When it has examined all of the pixels, the program displays the result image.
The result image highlights differences between the two input images no matter how small the differences are. If a pixel in one image has RGB values 50, 150, 200 and the corresponding pixel in the other image has RGB values 51, 150, 200, the result shows the difference plainly even though you won't be able to tell the difference with your eyes in the original images.
Download the example to experiment with it and to see additional details.