Here is an example of how to do it.
Add a component TImage
, set an image in the Picture
property, of course, you can use a loading system for the image as you like, in the example case we will start the component already with a defined image! p>
Global Variable Declaration (I always prefer to do this):
num,
StartX,
StartY,
OldStartX,
OldStartY,
OldEndX,
OldEndY : Integer;
IsDown : Boolean;
JPG: TJpegImage;
Bmp,
Bmp1,
Bmp2 : TBitmap;
In event MouseDown
of component TImage
we will get the X and Y coordinates of the Mouse:
procedure TForm5.Image1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
IsDown := True;
StartX := X;
StartY := Y;
OldStartX := X;
OldStartY := Y;
OldEndX := X;
OldEndY := Y;
end;
Now in the MouseMove
event of the TImage
component we will draw the selection area:
procedure TForm5.Image1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
begin
if IsDown then
begin
Canvas.Pen.Style := psDot;
Canvas.Pen.Mode := pmNotXor;
Canvas.Rectangle(OldStartX, OldStartY, OldEndX, OldEndY);
OldEndX := X;
OldEndY := Y;
Canvas.Rectangle(StartX, StartY, X, Y);
end;
end;
Ready, we come to the final part, let's release the mouse button and save the image.
In event MouseUp
of component TImage
:
procedure TForm5.Image1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
IsDown := False;
Canvas.Pen.Style := psDot;
Canvas.Pen.Mode := pmNotXor;
Canvas.Rectangle(OldStartX, OldStartY, OldEndX, OldEndY);
Bmp := TBitmap.Create;
JPG := TJpegImage.Create;
JPG.Assign(Bmp);
num := 90;
Image1.Picture.LoadFromFile('D:\imagem_original.bmp');
image1.Picture.Bitmap.Canvas.Brush.Style := bsClear;
if not (Image1.Picture.Graphic is TBitmap) then
raise Exception.Create('A imagem não é um Bitmap');
Bmp2 := TBitmap(Image1.Picture.Graphic);
Bmp1 := TBitmap.Create;
try
Bmp1.Width := Abs(OldEndX - OldStartX);
Bmp1.Height := Abs(OldEndY - OldStartY);
Bmp1.Canvas.CopyRect(Rect(0, 0, Bmp1.Width, Bmp1.Height), Bmp2.Canvas, Rect(OldStartX, OldStartY, OldEndX, OldEndY));
Bmp1.SaveToFile('D:\imagem_recortada.bmp');
finally
Bmp1.Free;
end;
end;
Note that on this line I'm saving the image Automatically when I release the mouse button, you can easily customize this, test:
1 - Comment the line containing, Bmp1.SaveToFile('D:\imagem_recortada.bmp');
2 - Remove from section finally
o Bmp1.Free;
3 - Add in the Click event of a TButton component:
procedure TForm5.Button1Click(Sender: TObject);
begin
Bmp1.SaveToFile('D:\imagem_recortada.bmp');
Bmp1.Free;
end;
Of course, you can use SavePictureDialog
to become more professional!
Ready!