Search code examples
delphifiremonkeydelphi-10.2-tokyo

How crop bitmap in selected area using firemonkey?


I need create a crop effect to my app. I have a TRectangle over a TImage, and I need when the user press the save button, copy just the area that the TRectangle uses. There is some way that I can cut just a specific area from the Image1.Bitmap? I printed a image to better ilustrate what I need:

enter image description here


Solution

  • Here is a sample that works for me:

    procedure TForm1.Button1Click(Sender: TObject);
    var
      Bmp: TBitmap;
      xScale, yScale: extended;
      iRect: TRect;
    begin
    
      Bmp := TBitmap.Create;
      xScale := Image1.Bitmap.Width / Image1.Width;
      yScale := Image1.Bitmap.Height / Image1.Height;
      try
        Bmp.Width := round(Rectangle1.Width * xScale);
        Bmp.Height := round(Rectangle1.Height * yScale);
        iRect.Left := round(Rectangle1.Position.X * xScale);
        iRect.Top := round(Rectangle1.Position.Y * yScale);
        iRect.Width := round(Rectangle1.Width * xScale);
        iRect.Height := round(Rectangle1.Height * yScale);
        Bmp.CopyFromBitmap(Image1.Bitmap, iRect, 0, 0);
        Image2.Bitmap := Bmp
      finally
        Bmp.Free;
      end;
    end;
    

    I assume here that Rectangle1 has Image1 as its Parent:

    enter image description here

    Otherwise you will need to consider the offset of Position.X and Position.Y properties.

    Here is a result of procedure functioning: enter image description here