寻找Zihuatanejo

C#编程小实例(二)(Compare two images with C# 用C#比较两个图片)(未看)

This is a snippet to compare 2 images to see if they are the same. This method first converts each Bitmap to a byte array, then gets the hash of each array. We then loop through each in the hash to see if they match

 

Language: C#

Last Modified: January 7, 2009
Instructions: Need a reference to the following:

System.Drawing
System.Security.Cryptography

Provide the method with 2 bitmaps

Snippet


  1. /// <summary>
  2. /// method for comparing 2 images to see if they are the same. First
  3. /// we convert both images to a byte array, we then get their hash (their
  4. /// hash should match if the images are the same), we then loop through
  5. /// each item in the hash comparing with the 2nd Bitmap
  6. /// </summary>
  7. /// <param name="bmp1"></param>
  8. /// <param name="bmp2"></param>
  9. /// <returns></returns>
  10. public bool doImagesMatch(ref Bitmap bmp1, ref Bitmap bmp2)
  11. {
  12.     try
  13.     {
  14.         //create instance or System.Drawing.ImageConverter to convert
  15.         //each image to a byte array
  16.         ImageConverter converter = new ImageConverter();
  17.         //create 2 byte arrays, one for each image
  18.         byte[] imgBytes1 = new byte[1];
  19.         byte[] imgBytes2 = new byte[1];
  20.  
  21.         //convert images to byte array
  22.         imgBytes1 = (byte[])converter.ConvertTo(bmp1, imgBytes2.GetType());
  23.         imgBytes2 = (byte[])converter.ConvertTo(bmp2, imgBytes1.GetType());
  24.  
  25.         //now compute a hash for each image from the byte arrays
  26.         SHA256Managed sha = new SHA256Managed();
  27.         byte[] imgHash1 = sha.ComputeHash(imgBytes1);
  28.         byte[] imgHash2 = sha.ComputeHash(imgBytes2);
  29.  
  30.         //now let's compare the hashes
  31.         for (int i = 0; i < imgHash1.Length && i < imgHash2.Length; i++)
  32.         {
  33.             //whoops, found a non-match, exit the loop
  34.             //with a false value
  35.             if (!(imgHash1[i] == imgHash2[i]))
  36.                 return false;
  37.         }
  38.     }
  39.     catch (Exception ex)
  40.     {
  41.         MessageBox.Show(ex.Message);
  42.         return false;
  43.     }
  44.     //we made it this far so the images must match
  45.     return true;
  46. }

posted on 2009-01-23 17:14  Zihuatanejo  阅读(468)  评论(0)    收藏  举报

导航