// Compare TBitmaps example. // efg, www.efg2.com/Lab // October 2000 unit ScreenComparison; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) ButtonCompare: TButton; procedure ButtonCompareClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.DFM} // For bitmaps of the same size, count the number of pixels that match // and the number that are different. PROCEDURE CompareBitmaps(CONST BitmapA, BitmapB: TBitmap; VAR Total, Match, Differ: INTEGER); TYPE TRGBTripleArray = ARRAY[WORD] OF TRGBTriple; pRGBTripleArray = ^TRGBTripleArray; VAR i : INTEGER; j : INTEGER; rowA: pRGBTripleArray; rowB: pRGBTripleArray; BEGIN ASSERT( (BitmapA.width = BitmapB.width) AND (BitmapA.height = BitmapB.height), 'Different sizes'); // Force bitmaps to have the same pf24bit Pixelformat // (this may be undesirable, for example, for large pf1bit bitmaps) BitmapA.PixelFormat := pf24bit; BitmapB.PixelFormat := pf24bit; Total := BitmapA.width * BitmapA.height; Match := 0; Differ := 0; FOR j := 0 TO BitmapA.height-1 DO BEGIN rowA := BitmapA.Scanline[j]; rowB := BitmapB.Scanline[j]; FOR i := 0 TO BitmapA.width-1 DO BEGIN {$IFDEF DELPHI5} {$DEFINE SIMPLEWAY} {$ENDIF} {$IFDEF DELPHI6} // should work in D6 {$DEFINE SIMPLEWAY} {$ENDIF} {$IFDEF SIMPLEWAY} // update this for D7 or later // new easy way for D5 or later (actually D4.02 and later) IF rowA[i] = rowB[i] THEN INC(Match) ELSE INC(Differ) {$ELSE} // D3 and D4 cannot use "simple" way // "bug" in earlier versions forces more code for test IF (rowA[i].rgbtRed = rowB[i].rgbtRed) AND (rowA[i].rgbtGreen = rowB[i].rgbtGreen) AND (rowA[i].rgbtBlue = rowB[i].rgbtBlue) THEN INC(Match) ELSE INC(Differ) {$ENDIF} END END END {CompareBitmaps}; procedure TForm1.ButtonCompareClick(Sender: TObject); VAR Bitmap1: TBitmap; Bitmap2: TBitmap; PixelsDiffer: INTEGER; PixelsMatch : INTEGER; PixelsTotal : INTEGER; begin Bitmap1 := TBitmap.Create; Bitmap2 := TBitmap.Create; TRY Bitmap1.LoadFromFile('yelflwr1.bmp'); Bitmap2.LoadFromFile('yelflwr2.bmp'); CompareBitmaps(Bitmap1, Bitmap2, PixelsTotal, PixelsMatch, PixelsDiffer); // Sample output: Total=307200, Match=265, Differ=306935 ShowMessage(Format('Total=%d, Match=%d, Differ=%d', [PixelsTotal, PixelsMatch, PixelsDiffer])); FINALLY Bitmap1.Free; Bitmap2.Free END end; end.