Delphi将图片缩放成指定大小

时间:2022-07-20 19:48:51
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls,jpeg, ExtCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    imgEdit: TImage;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject); 
var
  bitCut: TBitmap;
  bitEdit: TBitmap;
  picOriginal: TPicture;
begin  
  picOriginal := TPicture.Create;
  picOriginal.LoadFromFile(ExtractFilePath(ParamStr(0)) + '1.jpg'); //fileName为jpg文件路径

  bitCut := TBitmap.Create;
  bitCut.Width := 100;  //355
  bitCut.Height := 441;
  bitCut.Canvas.StretchDraw(Rect(0, 0, bitCut.Width, bitCut.Height), picOriginal.Graphic);
  bitEdit := TBitmap.Create;
  bitEdit.Width := picOriginal.Width;

//  bitCut.Canvas.CopyRect(Rect(0, 0, bitCut.Width, bitCut.Height),
//    bitEdit.Canvas, Rect(801, 149, 2595, 2359));

  imgEdit.Picture.Bitmap.Assign(bitCut);
  // 该释放的对象要释放
  bitEdit.Free;
  bitCut.Free;
  picOriginal.Free;
end;


procedure TForm1.Button2Click(Sender: TObject);
var
MyJpeg: TJpegImage;
Bmp,Bmp2:TBitmap;
begin
  MyJpeg:= TJpegImage.Create;
  MyJpeg.LoadFromFile(ExtractFilePath(ParamStr(0)) + '2.jpg'); // 1600* 900
  Bmp:=TBitmap.create;
  Bmp.Width:=1024;
  Bmp.Height:=768;   
  Bmp.Canvas.StretchDraw(Rect(0,0,Bmp.Width,Bmp.Height),MyJpeg);  
  Canvas.Draw(0,0,Bmp);
  Canvas.Draw(100,100,MyJpeg);
  Bmp.SaveToFile('2.bmp');
  Bmp.Free;
  MyJpeg.Free;  
end;

end.