2012-02-07 6 views
8

TBitmap을 가지고 있고이 비트 맵에서 자른 이미지를 얻고 싶다면 "제자리에서 자르기"작업을 수행 할 수 있습니까? 예 : 800x600 인 비트 맵을 가지고 있다면 어떻게하면 600x400 이미지가 가운데에 있는지, 즉 결과 TBitmap이 600x400이고 (100, 100) 및 (700)으로 묶인 사각형으로 구성되도록 줄일 수 있습니다. , 500) 원본 이미지에?Delphi - 어떻게 비트 맵을 자르려면?

다른 비트 맵을 사용해야하거나 원래 비트 맵에서이 작업을 수행 할 수 있습니까?

답변

20

당신은이 코드를 시도 BitBlt 기능

를 사용할 수 있습니다. 같은 비트 맵을 사용하려면

procedure CropBitmap(InBitmap, OutBitMap : TBitmap; X, Y, W, H :Integer); 
begin 
    OutBitMap.PixelFormat := InBitmap.PixelFormat; 
    OutBitMap.Width := W; 
    OutBitMap.Height := H; 
    BitBlt(OutBitMap.Canvas.Handle, 0, 0, W, H, InBitmap.Canvas.Handle, X, Y, SRCCOPY); 
end; 

하고이 방법으로 사용할 수는

Var 
    Bmp : TBitmap; 
begin 
    Bmp:=TBitmap.Create; 
    try 
    CropBitmap(Image1.Picture.Bitmap, Bmp, 10,0, 150, 150); 
    //do something with the cropped image 
    //Bmp.SaveToFile('Foo.bmp'); 
    finally 
    Bmp.Free; 
    end; 
end; 

, 기능

procedure CropBitmap(InBitmap : TBitmap; X, Y, W, H :Integer); 
begin 
    BitBlt(InBitmap.Canvas.Handle, 0, 0, W, H, InBitmap.Canvas.Handle, X, Y, SRCCOPY); 
    InBitmap.Width :=W; 
    InBitmap.Height:=H; 
end; 

이 버전을 시도하고이 방법으로 사용

Var 
Bmp : TBitmap; 
begin 
    Bmp:=Image1.Picture.Bitmap; 
    CropBitmap(Bmp, 10,0, 150, 150); 
    //do somehting with the Bmp 
    Image1.Picture.Assign(Bmp); 
end; 
+0

고마워요. 두 번째 비트 맵을 필요로하지 않고이 작업을 수행하는 간단한 방법이 있습니까? 델파이의'Move' 루틴과 중복되는 소스와 목적지를 처리하는 것과 같은 방식으로, 2 차원 적으로 같은 것이 있습니까? – rossmcm

+0

TBitmap의 ScanLine 속성과 함께 Move를 사용할 수 있지만 BitsPerPixel에 따라 픽셀의 바이트 크기를 계산해야합니다 –

+0

두 번째 옵션이 하나의 비트 맵 만 사용하는지 확인하십시오. – RRUZ

4

대답은 이미 허용되었지만 GDI 호출 대신 VCL 래퍼를 사용하는 내 버전을 작성한 이후로 그냥 던지기 만하면됩니다.

procedure TForm1.FormClick(Sender: TObject); 
var 
    Source, Dest: TRect; 
begin 
    Source := Image1.Picture.Bitmap.Canvas.ClipRect; 
    { desired rectangle obtained by collapsing the original one by 2*2 times } 
    InflateRect(Source, -(Image1.Picture.Bitmap.Width div 4), -(Image1.Picture.Bitmap.Height div 4)); 
    Dest := Source; 
    OffsetRect(Dest, -Dest.Left, -Dest.Top); 
    { NB: raster data is preserved during the operation, so there is not need to have 2 bitmaps } 
    Image1.Picture.Bitmap.Canvas.CopyRect(Dest, Image1.Picture.Bitmap.Canvas, Source); 
    { and finally "truncate" the canvas } 
    Image1.Picture.Bitmap.Width := Dest.Right; 
    Image1.Picture.Bitmap.Height := Dest.Bottom; 
end; 
관련 문제