Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 418
isa Avatar asked Aug 29 '09 20:08

isa


2 Answers

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.

like image 96
Cesar Romero Avatar answered Oct 11 '22 22:10

Cesar Romero


Using ScanLine, Without TMemoryStream.

function IsSameBitmapUsingScanLine(Bitmap1, Bitmap2: TBitmap): Boolean;
var
 i           : Integer;
 ScanBytes   : Integer;
begin
  Result:= (Bitmap1<>nil) and (Bitmap2<>nil);
  if not Result then exit;
  Result:=(bitmap1.Width=bitmap2.Width) and (bitmap1.Height=bitmap2.Height) and (bitmap1.PixelFormat=bitmap2.PixelFormat) ;

  if not Result then exit;

  ScanBytes := Abs(Integer(Bitmap1.Scanline[1]) - Integer(Bitmap1.Scanline[0]));
  for i:=0 to Bitmap1.Height-1 do
  Begin
    Result:=CompareMem(Bitmap1.ScanLine[i],Bitmap2.ScanLine[i],ScanBytes);
    if not Result then exit;
  End;

end;

Bye.

like image 34
RRUZ Avatar answered Oct 11 '22 22:10

RRUZ