The following tutorial will demonstrate how to create a C# sample program to identify if the images are identical or different. Indeed, comparing images is really easy by using C#.

1. Let’s start a new project using VS C# 2010 express.

2. Select Windows Form Application. you may give any name to this project.

3. Insert the following control to the form in design mode.

  • 2 PictureBox
  • 3 Buttons
  • 1 OpenFileDialog
You may place the control at any location. My form design is something look like the following screenshot.

C# Image Compare Example

4. Create click event for all the buttons by double click the button from design view.

5. Make sure that you switch to code view now.

6. Add the following directive. We will need to utilize the memory steam in this tutorial.

using System.IO;

7. Enter the following code to the click event method for button1 & button2 so that it open a file dialog. The picture box control will display the image from the selected image file from the file dialog.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
private void button1_Click(object sender, EventArgs e)
{
  DialogResult result = openFileDialog1.ShowDialog();
  if (result == DialogResult.OK)
  {
    Image image = Image.FromFile(openFileDialog1.FileName);
    pictureBox1.Image = image;
  }
}

private void button2_Click(object sender, EventArgs e)
{
  DialogResult result = openFileDialog1.ShowDialog();
  if (result == DialogResult.OK)
  {
    Image image = Image.FromFile(openFileDialog1.FileName);
    pictureBox2.Image = image;
  }
}

8. Enter the following code to the click event method for button3. This is the compare button where it will check if the images are identical or different. Basically, it save the images into memory stream and convert the stream to Base64 string. Binary data with similar content will have similar string. In case it is different, then it mean the content is different too.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
private void button3_Click(object sender, EventArgs e)
{
  MemoryStream ms = new MemoryStream();

  pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
  String image_one = Convert.ToBase64String(ms.ToArray());
  ms.Position = 0;

  pictureBox2.Image.Save(ms, pictureBox2.Image.RawFormat);
  String image_two = Convert.ToBase64String(ms.ToArray());
  ms.Close();

  if (image_one.Equals(image_two))
    MessageBox.Show("SAME");
  else
    MessageBox.Show("DIFFERENT");
}

9. Compile and run the project and you should see something similar to the following screenshot.

C# Image Compare Example

Download source code: CompareImageApplication.zip