2012-06-23 37 views
1

我想將TBitMap轉換爲KOL中的PBitMap。TBitMap到PBitMap KOL

我試過,但我得到一個黑色的畫面作爲輸出:

function TbitMapToPBitMap (bitmap : TBitMap) : PbitMap; 
begin 
result := NIL; 
if Assigned(bitmap) then begin 
    result := NewBitmap(bitmap.Width, bitmap.Height); 
    result.Draw(bitmap.Canvas.Handle, bitmap.Width, bitmap.Height); 
end; 
end; 

任何想法有什麼錯呢?我正在使用Delphi7。

謝謝你的幫助。

編輯:新代碼:

function TbitMapToPBitMap (const src : TBitMap; var dest : PBitMap) : Bool; 
begin 
result := false; 
if ((Assigned(src)) and (Assigned (dest))) then begin 
dest.Draw(src.Canvas.Handle, src.Width, src.Height); 
result := true; 
end; 
end; 

procedure TForm1.Button1Click(Sender: TObject); 
var 
TBitMapTest : TBitMap; 
PBitMapTest : PBitMap; 
begin 
TBitMapTest := TBitMap.Create; 
TBitMapTest.LoadFromFile ('C:\test.bmp'); 
PBitMapTest := NewBitMap (TBitMapTest.Width, TBitMapTest.Height); 
TbitMapToPBitMap (TBitMapTest, PBitMapTest); 
PBitMapTest.SaveToFile ('C:\test2.bmp'); 
PBitMapTest.Free; 
TBitMapTest.Free; 
end; 
+1

關於您的編輯,您仍然將'Dest'繪製到'Source'。反之亦然。 – TLama

+0

我不明白:/我想將TBitMap轉換爲PBitmap。所以PBitMap是目的地,TBitMap是源。 –

+1

閱讀KOL的'TBitmap.Draw'函數所寫的內容:*繪製位圖給定的設備上下文。如果位圖是DIB ... *,那麼您將「Dest」繪製爲「Source」。 – TLama

回答

3

要回答你的問題,爲什麼是你的目標圖像的黑色;這是因爲你正在繪製這些目標圖像來源和黑色,因爲NewBitmap將圖像初始化爲黑色。如果你想KOL PBitmap如何複製或轉換我發現只有一種方法(也許我錯過了這樣的功能在KOL,但即使如此,在下面的代碼中使用的方法是非常有效的)。您可以使用Windows GDI函數進行位塊傳輸,即BitBlt,它只將指定區域從一個畫布複製到另一個畫布。

下面的代碼,當您單擊該按鈕時,將創建VCL和KOL位圖實例,將圖像加載到VCL位圖,調用VCL到KOL位圖複製函數,如果此函數成功,則將KOL位圖繪製到形成畫布並釋放兩個位圖實例:

uses 
    Graphics, KOL; 

function CopyBitmapToKOL(Source: Graphics.TBitmap; Target: PBitmap): Boolean; 
begin 
    Result := False; 
    if Assigned(Source) and Assigned(Target) then 
    begin 
    Result := BitBlt(Target.Canvas.Handle, 0, 0, Source.Width, Source.Height, 
     Source.Canvas.Handle, 0, 0, SRCCOPY); 
    end; 
end; 

procedure TForm1.Button1Click(Sender: TObject); 
var 
    KOLBitmap: PBitmap; 
    VCLBitmap: Graphics.TBitmap; 
begin 
    VCLBitmap := Graphics.TBitmap.Create; 
    try 
    VCLBitmap.LoadFromFile('d:\CGLIn.bmp'); 
    KOLBitmap := NewBitmap(VCLBitmap.Width, VCLBitmap.Height); 
    try 
     if CopyBitmapToKOL(VCLBitmap, KOLBitmap) then 
     KOLBitmap.Draw(Canvas.Handle, 0, 0); 
    finally 
     KOLBitmap.Free; 
    end; 
    finally 
    VCLBitmap.Free; 
    end; 
end; 
+1

太棒了!非常感謝你!我感謝你的工作! GUI中只有一個小故障,在後臺繪製實際的圖像:/ –

+1

當然,如果是這樣的話,您不必繪製位圖,我只是在畫布上使用了繪圖,僅用於測試目的。您可以直接使用'KOLBitmap.SaveToFile'並刪除'KOLBitmap.Draw'。 – TLama

+1

aaah我忘記了KolBitMap.Draw將位圖繪製到第一個參數>。<我應該牢記這一點!再一次非常感謝你! –

相關問題