In this
blog post, i will show you the quickest way to identify whether 2 images are
identical or different using C#.
As a first
step in determining whether 2 images are identical or not, we use the file size
information for basic comparison. However what happens when 2 different images
have same file size. In this case you cannot determine the difference using
file size.
Following are
several approaches in comparing the images.
- Comparing hash of the image
- Comparing byte by byte
- Comparing pixel by pixel etc..,
In the
above approaches, 1st one comparing the hash of the images is the
fastest technique to determine whether the images are different.
Image Hash Comparison:
Step 1: Find the hash of the given
image
Using any
hashing technique supported in C#, compute the hash of the image by providing
image bytes as argument. This will create a 32 bytes hash.
Code
Snippet:
HMACSHA1 hmacSha1 = new HMACSHA1();
byte[] imageHash = hmacSha1.ComputeHash(ImageBytes);
Note:
Here ComputeHash() method will always generate 32 bytes of hash
irrespective of the size of the image.
Step 2: Compare the calculated 32
bytes hash (byte by
byte) and if any byte differs you can stop the comparison and return that the
images are not equal.
Code
Snippet:
private bool
IsImageEqual(byte[] imageHash1, byte[] imageHash2)
{
bool isImageEqual = true;
//Compare the hash values
for (int j = 0; j
< imageHash1.Length && j < imageHash2.Length; j++)
{
if (imageHash1[j] != imageHash2[j])
{
isImageEqual = false;
break;
}
}
return isImageEqual;
}
No comments:
Post a Comment