Compare images in C#

Do you end up with 17 different versions of a single image you took on your phone, when you try to clear up space and copy over everything to your system? I do. With the different folders they make their way into, in the name of backups and the various locations they get uploaded into, I usually end up with way too many copies of the same images – with different names!

So here’s a quick tool to identify duplicate images in a given folder. The code only compares 2 diagonal lines through the images, and has worked really well for me. Ofcourse, this will only work for images with same resolution (identical images identification only).

Complete pixel by pixel match took way too much time, so I then used this approach successfully!

filesInFolder = Directory.GetFiles(selectedPath);
List imagesInFolder = filesInFolder.Where(i => i.EndsWith(“.jpg”, true, CultureInfo.CurrentCulture)
|| i.EndsWith(“.png”, true, CultureInfo.CurrentCulture)
|| i.EndsWith(“.jpeg”, true, CultureInfo.CurrentCulture)).ToList();

bool foundDuplicate;
Duplicate duplicate;
int deletedCount = 0;
int processedCount = 0;

List duplicateImagesInfo = new List();

foreach (string baseImage in imagesInFolder)
{
if (!duplicateImagesInfo.Any(d => d.DuplicateFilePaths.Any(p => p.Contains(baseImage))))
{
foundDuplicate = false;
duplicate = new Duplicate {DuplicateFilePaths = new List()};

foreach (string compareImage in imagesInFolder.Where(i => i != baseImage))
{
if (IsDuplicateImage(baseImage, compareImage))
{
foundDuplicate = true;
duplicate.DuplicateFilePaths.Add(compareImage);
File.Delete(compareImage);
deletedCount++;
}
}

if (foundDuplicate)
{
duplicate.DuplicateFilePaths.Add(baseImage);
duplicateImagesInfo.Add(duplicate);
}
}

processedCount++;
}
lblSelectedFolder.Text += ” ” + deletedCount + ” duplicate images deleted!”;
}

private bool IsDuplicateImage(string baseImagePath, string compareImagePath)
{
if (!File.Exists(baseImagePath) || !File.Exists(compareImagePath))
{
return false;
}

bool isDuplicate = true;
using (var baseImage = new Bitmap(baseImagePath))
{
using (var compareImage = new Bitmap(compareImagePath))
{
if (baseImage.Width == compareImage.Width && baseImage.Height == compareImage.Height)
{
int xBase = baseImage.Width / baseImage.Height;
for (int y = 0; y < baseImage.Height; y++)
{
if (baseImage.GetPixel(xBase * y, y).ToString() != compareImage.GetPixel(xBase * y, y).ToString())
{
isDuplicate = false;
break;
}
}
return isDuplicate;
}
return false;
}
}
}
}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s