Thursday, September 25, 2008

A Brute-Force Duplicate Images Comparison


In this post a simple function is presented that runs a brute-force comparer to find whether two images/photos are exactly the same or not. It works well but not optimal.

using System.Drawing;
using System.Drawing.Imaging;
using System;
namespace Fabriclake.Imaging
{

internal class IntelliPhoto
{
/// <summary>
/// It runs a brute-force comparer to find whether two
/// images/photos are identical or not. It works well
/// but not optimal.
/// Author: G. R. Roosta
/// License: Free To Use (No Restriction)
/// </summary>
/// <param name="photo1">The first image/photo to compare</param>
/// <param name="photo2">The second image/photo to compare</param>
/// <returns>True if two images are identical</returns>
public static bool Identical(Bitmap photo1, Bitmap photo2)
{
int rows = photo1.Height;
int cols = photo1.Width;
if (photo2.Width != cols photo2.Height != rows)
return false;
BitmapData bmpData1 = photo1.LockBits(new Rectangle(0, 0, cols, rows), ImageLockMode.ReadWrite, photo1.PixelFormat);
BitmapData bmpData2 = photo2.LockBits(new Rectangle(0, 0, cols, rows), ImageLockMode.ReadWrite, photo2.PixelFormat);
int stride1 = bmpData1.Stride;
int stride2 = bmpData2.Stride;
IntPtr scan1 = bmpData1.Scan0;
IntPtr scan2 = bmpData2.Scan0;

unsafe
{
byte* p1 = (byte*)(void*)scan1;
byte* p2 = (byte*)(void*)scan2;
int cols3 = cols * 3;
int offs = stride1 - cols3;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols3; j++)
{
if (p1[0] != p2[0])
{
photo1.UnlockBits(bmpData1);
photo2.UnlockBits(bmpData2);
return false;
}
p1++;
p2++;
}
p1 += offs;
p2 += offs;
}
} // end unsafe

photo1.UnlockBits(bmpData1);
photo2.UnlockBits(bmpData2);
return true;
} // end of function
}
}

2 comments:

  1. if this.ViewState["xxx"] is not a string, "as string" will return null. .ToString() will try to convert any other type to string by calling the object's .ToString() method.

    ReplyDelete
  2. In object-oriented programming, the open/closed principle states "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification"

    ReplyDelete