Compare Bitmaps - CSharp System.Drawing

CSharp examples for System.Drawing:Bitmap

Description

Compare Bitmaps

Demo Code


using System.Drawing;
using System.Drawing.Imaging;
using System;//from   w  ww .j  a  va2 s . c o  m

public class Main{
        public static CompareResult CompareBitmaps(Bitmap ReferenceBitmap, Bitmap OutputBitmap, double Threshold = 0.01)
      {
         var CompareResult = default(CompareResult);

         if (ReferenceBitmap.Size == OutputBitmap.Size)
         {
            CompareResult.PixelTotalDifference = 0;
            CompareResult.DifferentPixelCount = 0;
            CompareResult.TotalPixelCount = 0;
            for (int y = 0; y < ReferenceBitmap.Height; y++)
            {
               for (int x = 0; x < ReferenceBitmap.Width; x++)
               {
                  Color ColorReference = ReferenceBitmap.GetPixel(x, y);
                  Color ColorOutput = OutputBitmap.GetPixel(x, y);
                  int Difference3 = (
                     Math.Abs((int)ColorOutput.R - (int)ColorReference.R) +
                     Math.Abs((int)ColorOutput.G - (int)ColorReference.G) +
                     Math.Abs((int)ColorOutput.B - (int)ColorReference.B)
                  );
                  CompareResult.PixelTotalDifference += Difference3;
                  if (Difference3 > 6)
                  {
                     CompareResult.DifferentPixelCount++;
                  }
                  CompareResult.TotalPixelCount++;
               }
            }

            var PixelTotalDifferencePercentage = (double)CompareResult.DifferentPixelCount * 100 / (double)CompareResult.TotalPixelCount;
            CompareResult.Equal = (PixelTotalDifferencePercentage < Threshold);
         }

         return CompareResult;
      }
}

Related Tutorials