Compare image against an array of images

1.1k views Asked by At

I have an image located in

C:\ImageOne.png

And I have lets say 20 images in the directory

C:\Images

How can I compare ImageOne.png against all those images?

Example:

Imagine i got one reCaptcha image saved as C:\ImageOne.png

And in a folder located at C:\Images i have other reCaptcha images.

I then need a code that can find a identical image inside C:\Images

Current Code:

public static bool ImageCompareString(Bitmap firstImage, Bitmap secondImage)
{
    MemoryStream ms = new MemoryStream();
    firstImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
    String firstBitmap = Convert.ToBase64String(ms.ToArray());
    ms.Position = 0;

    secondImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
    String secondBitmap = Convert.ToBase64String(ms.ToArray());

    if (firstBitmap.Equals(secondBitmap))
    {
        return true;
    }
    else
    {
        return false;
    }
}

Bitmap img2 = new Bitmap(@"C:\ImageOne");

private void CheckCaptcha()
{
    foreach (string s in Directory.GetFiles(@"C:\Images"))
    {
        Bitmap img1 = new Bitmap(s);

        if (ImageCompareString(img1, img2) == true)
        {
            Logging("Identical");
        }
        else
        {
            Logging("Not Identical");
        }
        img1.Dispose();
    }
}
1

There are 1 answers

11
Selman Genç On BEST ANSWER

Maybe this will help:

Bitmap img2 = new Bitmap(@"C:\ImageOne.png");
ImageConverter converter = new ImageConverter();
byte[] img2Bytes = (byte[])converter.ConvertTo(img2, typeof(byte[]));

foreach (string s in Directory.GetFiles(@"C:\Images"))
{
    Bitmap img1 = new Bitmap(s);
    byte[] img1Bytes = (byte[])converter.ConvertTo(img1, typeof(byte[]));
    if (CompareImages(img1Bytes,img2Bytes))
    {
        Logging("Identical");
    }
    else
    {
        Logging("Not Identical");
    }
    img1.Dispose();
}

public bool CompareImages(byte[] b1, byte[] b2)
{
   EqualityComparer<byte> comparer = EqualityComparer<byte>.Default;
   if (b1.Length == b2.Length)
   {
       for (int i = 0; i < b1.Length; i++)
       {
           if (!comparer.Equals(b1[i], b2[i])) return false;
       }
    } else { return false; }

     return true;
}