Como comparar 2 Imagens
ago.29, 2009 in
Delphi, Dicas, Programação
O código a seguir, está comparando 2 bitmaps, mas a idéia pode ser utilizada para comparar outros formatos de imagem, arquivos, ou qualquer conteúdo salvo em TMemoryStream.
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;
Aqui uma outra versão usando scanline, postada por RRUZ no stackoverflow.com
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

Leave a Reply