This is my program code for comparing if 2 images are the same. It basically uses the open dialog and opens 1 image at a time and puts it in 1 picture box.
I heard that GetPixel()
method may be slow. Is there a more efficient and faster way to compare 2 if 2 images are the same?
Bitmap image1 = null;
Bitmap image2 = null;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e) //first image open
{
OpenFileDialog openDialog = new OpenFileDialog();
if (openDialog.ShowDialog() == DialogResult.OK)
{
image1 = new Bitmap(openDialog.FileName);
pictureBox1.Image = image1;
}
}
private void button2_Click(object sender, EventArgs e) //second image open
{
OpenFileDialog openDialog = new OpenFileDialog();
if (openDialog.ShowDialog() == DialogResult.OK)
{
image2 = new Bitmap(openDialog.FileName);
pictureBox2.Image = image2;
}
}
private void button3_Click(object sender, EventArgs e) //compare button
{
if (compare(image1, image2))
{
MessageBox.Show("Same Image.");
}
else
{
MessageBox.Show("Different Image.");
}
}
private bool compare(Bitmap bmp1, Bitmap bmp2)
{
bool equals = true;
bool flag = true; //Inner loop isn't broken
//Test to see if we have the same size of image
if (bmp1.Size == bmp2.Size)
{
for (int x = 0; x < bmp1.Width; ++x)
{
for (int y = 0; y < bmp1.Height; ++y)
{
if (bmp1.GetPixel(x, y) != bmp2.GetPixel(x, y))
{
equals = false;
flag = false;
break;
}
}
if (!flag)
{
break;
}
}
}
else
{
equals = false;
}
return equals;
}
Bitmap
inherits fromImage
, which implementsIDisposable
. This means you very much better callDispose()
on those objects are you are done with them (way many paths here with UI event handlers), or put them intousing
blocks. \$\endgroup\$OpenFileDialog
. I'll probably post an answer to show some of this. \$\endgroup\$