How to compare if 2 images are the same using Hash bytes?

private void button1_Click(object sender, EventArgs e)
{
    Bitmap im1 = new Bitmap(@"C:\Users\user\Downloads\CaptchaCollection\1.png");
    Bitmap im2 = new Bitmap(@"C:\Users\user\Downloads\CaptchaCollection\2.png");

    if (HashImage(im1) == HashImage(im2))
    {
        MessageBox.Show("Same Image");
    }

    else
    {
        MessageBox.Show("Different Image");
    }
}

If you click on the button, it compares these 2 images.

Here is the code that is used to hash the image.

public byte[] HashImage(Bitmap image)
{
    var sha256 = SHA256.Create();

    var rect = new Rectangle(0, 0, image.Width, image.Height);
    var data = image.LockBits(rect, ImageLockMode.ReadOnly, image.PixelFormat);

    var dataPtr = data.Scan0;

    var totalBytes = (int)Math.Abs(data.Stride) * data.Height;
    var rawData = new byte[totalBytes];
    System.Runtime.InteropServices.Marshal.Copy(dataPtr, rawData, 0, totalBytes);

    image.UnlockBits(data);

    return sha256.ComputeHash(rawData);
}

So, how do I use the method HashImage()to compare both of these images if they are the same visually or not?

I tried to compare 2 images that are clearly the same, but they do not work in order to compare correctly. Instead, I get a different image.

I even tried this, but it doesn't work either.

if (HashImage(im1).Equals(HashImage(im2)))

UPDATE: I tried this, but it doesn't work either.

if (ReferenceEquals(HashImage(im1),HashImage(im2)))
+4
source share
1 answer

I know 3 ways to compare byte array:

  • []. SequenceEqual ( [])
  • System.Text.Encoding.UTF8.GetString(byte []) ==
  • Convert.ToBase64String (byte []) ==

:

   Console.WriteLine("SEQUENCE EQUAL: " + (HashImage(im1).SequenceEqual(HashImage(im2)) ? "TRUE" : "FALSE") + " (easiest way)");
   Console.WriteLine("UTF8 STRING:    " + (System.Text.Encoding.UTF8.GetString(HashImage(im1)) == System.Text.Encoding.UTF8.GetString(HashImage(im2)) ? "TRUE" : "FALSE") + " (conversion to utf string - not good for display or hash, good only for data from UTF8 range)");
   Console.WriteLine("HASH STRING:    " + (Convert.ToBase64String(HashImage(im1)) == Convert.ToBase64String(HashImage(im2)) ? "TRUE" : "FALSE") + " (best to display)");

   Console.WriteLine("1: " + Convert.ToBase64String(HashImage(im1)));
   Console.WriteLine("2: " + Convert.ToBase64String(HashImage(im2)));

Bitmap im2 . , .

: System.Text.Encoding.UTF8.GetString (- ). . @CodesInChaos .

+3

Source: https://habr.com/ru/post/1523993/


All Articles