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