【问题标题】:How to crop an FMX TBitmap如何裁剪 FMX TBitmap
【发布时间】:2015-09-18 12:29:22
【问题描述】:

我通过 TCameraComponent.SampleBufferReady 事件收到位图。然后我需要裁剪接收到的图像,以便获得例如矩形图像。

我用以下方法计算必要的参数:

procedure TPersonalF.SampleBufferReady(Sender: TObject;
  const ATime: TMediaTime);
var
  BMP: TBitmap;
  X, Y, W, H: Word;
begin
  Try
    BMP := TBitmap.Create;
    CameraComponent.SampleBufferToBitmap(BMP, true);
    if BMP.Width >= BMP.Height then //landscape
    begin
      W:=BMP.Height;
      H:=W;
      Y:=0;
      X:=trunc((BMP.Width-BMP.Height)/2);
    end
    else //portrait
    begin
      W:=BMP.Width;
      H:=W;
      X:=0;
      Y:=trunc((BMP.Height-BMP.Width)/2);
    end;
    CropBitmap(BMP, Image1.Bitmap, X,Y,W,H);
  Finally
    BMP.Free;
  End;
end; 

我找到了@RRUZ delphi-how-do-i-crop-a-bitmap-in-place 的答案,但它需要 VCL API 句柄并且使用 Windows GDI 函数:

procedure CropBitmap(InBitmap, OutBitMap: TBitmap; X, Y, W, H: Word);
  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;

我的项目正在使用 FMX,我计划将来将其移植到 Android 平台。因此,如果我使用句柄,我预计会遇到问题。我怎么解决这个问题?

【问题讨论】:

    标签: delphi bitmap crop firemonkey tbitmap


    【解决方案1】:

    假设你可以保证 InBitmap 和 OutBitMap 存在(如果不存在,你可以自己处理错误检查)

    procedure CropBitmap(InBitmap, OutBitMap: TBitmap; X, Y, W, H: Word);
    var
      iRect : TRect;
    begin
        OutBitMap.PixelFormat := InBitmap.PixelFormat;
        OutBitMap.Width := W;
        OutBitMap.Height := H;
        iRec.Left := 0;
        iRect.Top := 0;
        iRect.Width := W;
        iRect.Height := H;
        OutBitMap.CopyFromBitmap( InBitMap, iRect, 0, 0 );
    end;
    

    它与原版相同,但使用了类似于 Windows 的 Firemonkey CopyFromBitmap,但隐晦地命名为 BitBlt。

    【讨论】:

    • 非常感谢@Dsm,它几乎可以工作,虽然它不接受OutBitMap.PixelFormat := InBitmap.PixelFormat;,因为它是一个只读属性。有两个名为CopyFromBitmap 的重载方法,我只看到第一个,它有一个参数(const Source:TBitmap),所以它确实适合我。再次感谢您!
    • 抱歉 - 我没有检查 PixelFormat 属性 - 我只是从原始代码中剪切和粘贴 :blush:
    猜你喜欢
    • 2011-02-07
    • 2011-07-25
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    • 1970-01-01
    • 2013-08-10
    • 2012-11-16
    相关资源
    最近更新 更多