2009-08-29 38 views

回答

16

可以節省位圖到內存流和使用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; 

我沒有這個基準碼X掃描線,如果你這樣做,請讓我們知道哪一個是最快的。

+2

一些評論:1)代碼不是異常安全的。 2)如果位圖的寬度或高度不同,我會立即返回False。或者,即使像素格式不同,但問題太模糊不清。 – mghie 2009-08-29 21:35:54

+0

好評mghie。我改變代碼來測試高度和寬度。 – 2009-08-29 21:46:27

+0

吞嚥異常不是我的意思,讓我編輯代碼... – mghie 2009-08-29 21:51:14

0

如果你需要一個準確的答案,沒有。如果你需要一個近似值,你可能會檢查一個像素的選擇。但是如果你想知道兩個位圖是否完全相同,你需要比較整個像素和像素格式的數據。

11

使用ScanLine,無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; 

再見。

+0

+1非常好地組成。比較這個與Cesar的解決方案的速度會很有趣。這有更多的比較,但通過不分配內存節省時間。問題標題確實指定了**最快的**,畢竟。 – Argalatyr 2009-08-30 01:45:00

+1

@RRUZ:我同意這是一個很好的解決方案,如果相同的位圖意味着相同的內存佈局+1。儘管如此,我認爲儘快檢查可能不同格式的相同位圖是一個更有趣的問題。如果pf24bit或pf32bit位圖的顏色少於256色,則將其保存爲pf8bit是合理的,但仍會顯示相同的位圖。 – mghie 2009-08-30 06:46:26

+0

我通常只使用pf8bit,爲此可以。我想知道如果對齊位被檢查,如果你有pf12bit和一個奇數的寬度。 bpp的8以下同樣,但是這些都是計劃的afaik。 – 2009-08-30 09:28:58

相關問題