Showing posts with label Comparison. Show all posts
Showing posts with label Comparison. Show all posts

Monday, 3 October 2011

Compare bitmaps images.

Here is the code to compare 2 bitmaps images.
public class ComparingImages
 {
   public enum CompareResult
   {
      Match,
      Mismatch,
      SizeMismatch
   };

public static CompareResult Compare(Bitmap bmp1, Bitmap bmp2)
 {
   CompareResult cr = CompareResult.Match;
   //Test to see if we have the same size of image
   if (bmp1.Size != bmp2.Size)
   {
     cr = CompareResult.SizeMismatch;
   }
  else
  {
    //Convert each image to a byte array
    ImageConverter ic = new ImageConverter();
   byte[] btImage1 = new byte[1];
   btImage1 = (byte[])ic.ConvertTo(bmp1, btImage1.GetType());
   byte[] btImage2 = new byte[1];
   btImage2 = (byte[])ic.ConvertTo(bmp2, btImage2.GetType());
   //Compute a hash for each image
   var shaM = new SHA256Managed();
   byte[] hash1 = shaM.ComputeHash(btImage1);
   byte[] hash2 = shaM.ComputeHash(btImage2);
   //Compare the hash values
   for (int i = 0; i < hash1.Length && i < hash2.Length
   && cr == CompareResult.Match; i++)
   {
     if (hash1[i] != hash2[i])
     cr = CompareResult.Mismatch;
    }
   }
   return cr;
  }
  }

Thanks!
~jawed

Monday, 15 November 2010

Compare two Images File Using C#

Compare two Images File Using C#

In this post i m going to explain how to compare two images files using C#.
which would be very useful while performing Automation for checking whether two taken screen shot of web pages are same or not.

Below is the Code snippet which i have used for my automation purpose.

public void compareImages()
{
//First Image files
string Image1Location = @"C:\Pictures\For Website\DSCN0444.JPG";
//Second Image File
string Image2Location = @"C:\Pictures\For Website\DSCN0444.JPG";
try
{
string imageRef1, imageRef2;
//First Image BitMap
Bitmap img1Bitmap = new Bitmap(Image1Location);
//Second Image BitMap
Bitmap img2Bitmap = new Bitmap(Image2Location);
//Keep The Count of Pixel
int count1Pix = 0;
int count2Pix= 0;
//Decison whether Images are same or not
bool flag = true;
//Compare by Width
if (img1Bitmap.Width == img2Bitmap.Width)
{
//Compare by Height
if (img1Bitmap.Height == img2Bitmap.Height)
{
for (int i = 0; i < img1Bitmap.Width; i++)
{
for (int j = 0; j < img1Bitmap.Height; j++)
{
imageRef1 = img1Bitmap.GetPixel(i, j).ToString();
imageRef2 = img2Bitmap.GetPixel(i, j).ToString();
if (img1_ref != img2_ref)
{
count2Pix++;
flag = false;
break;
}
count1Pix++;
}
;
}
}
else
{
MessageBox.Show("Images are of Different Height");
}
}
else
{
MessageBox.Show("Images are of Different Width");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

if (flag == false)
MessageBox.Show("Image "+Image1Location+"and "+ Image2Location+"are not same , total wrong pixel found " + count2Pix );
else
MessageBox.Show("Image " + Image1Location + "and " + Image2Location + "are same!! Thank you");
}


Thanks,
Md.Jawed
jawed.ace@gmail.com