What is the fastest way to check if two Tbitmaps are the same?

delphi, delphi-2009

Solution

You can save both Bitmaps to TMemoryStream and compare using CompareMem:

function IsSameBitmap(Bitmap1, Bitmap2: TBitmap): Boolean;
var
 Stream1, Stream2: TMemoryStream;
begin
  Assert((Bitmap1 <> nil) and (Bitmap2 <> nil), 'Params can''t be nil');
  Result:= False;
  if (Bitmap1.Height <> Bitmap2.Height) or (Bitmap1.Width <> Bitmap2.Width) then
     Exit;
  Stream1:= TMemoryStream.Create;
  try
    Bitmap1.SaveToStream(Stream1);
    Stream2:= TMemoryStream.Create;
    try
      Bitmap2.SaveToStream(Stream2);
      if Stream1.Size = Stream2.Size Then
        Result:= CompareMem(Stream1.Memory, Stream2.Memory, Stream1.Size);
    finally
      Stream2.Free;
    end;
  finally
    Stream1.Free;
  end;
end;

begin
  if IsSameBitmap(MyImage1.Picture.Bitmap, MyImage2.Picture.Bitmap) then
  begin
    // your code for same bitmap
  end;
end;

I did not benchmark this code X scanline, if you do, please let us know which one is the fastest.

Problem

Is there a better way than examine them pixel by pixel?

Original source

Related problems