In this article, we will compare two images using the BitMap library in the dot net core application. Create one .net core Console application in Visual Studio and install the System.Drawing.The common library is either in NuGet Package Manager or the command line.
For the NuGet Package Manager Console, run the below command.
Install-Package System.Drawing.Common
For the .NET CLI command line, run the below command.
dotnet add package System.Drawing.Common
Basic image identification can be done with Hashing MD5 using the Cryptography library. For quick comparison generate a hash for each image and compare the image hashes and it will give the result.
Code Example
using System.Drawing;
using System.Security.Cryptography;
Console.WriteLine("Cryptography MD5 Quick Comparison ");
bool st= AreImagesIsIdentical(@"image1.PNG",@"image2.PNG");
Console.WriteLine("is Same image :" + st);
string GetImageHash(string imagePath)
{
using (var md5 = MD5.Create())
{
using (var stream = new FileStream(imagePath, FileMode.Open))
{
var hash = md5.ComputeHash(stream);
return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
}
}
}
bool AreImagesIdentical(string imagePath1, string imagePath2)
{
return GetImageHash(imagePath1) == GetImageHash(imagePath2);
}
Output
![Output]()
The bitmap library will help to compare pixels in the images. For comparing the pixel values of the two images, the code example is below.
using System.Drawing;
Console.WriteLine("Pixel Comparison ");
bool st= AreImagesIsIdentical(@"image1.PNG",@"image2.PNG");
bool AreImagesIsIdentical(string imagePath1, string imagePath2)
{
using (Bitmap bmp1 = new Bitmap(imagePath1))
using (Bitmap bmp2 = new Bitmap(imagePath2))
{
if (bmp1.Width != bmp2.Width || bmp1.Height != bmp2.Height)
{
return false;
}
for (int y = 0; y < bmp1.Height; y++)
{
for (int x = 0; x < bmp1.Width; x++)
{
if (bmp1.GetPixel(x, y) != bmp2.GetPixel(x, y))
{
return false;
}
}
}
}
return true;
}
Output
![Output2]()