How to resize a *.jpg image and save the result to a file #99

Question
How do I resize a *.jpg or *.gif image from say 640 × 480 to 50 × 50 and then save the image as a new one?
procedure TForm1.Button1Click(Sender: TObject);
var
  bmp: TBitmap;
  jpg: TJpegImage;
  scale: Double;
begin
  if opendialog1.execute then
  begin
    jpg := TJpegImage.Create;
    try
      jpg.Loadfromfile(opendialog1.filename);
      if jpg.Height > jpg.Width then
        scale := 50 / jpg.Height
      else
        scale := 50 / jpg.Width;
      bmp := TBitmap.Create;
      try
        {Create thumbnail bitmap, keep pictures aspect ratio}
        bmp.Width := Round(jpg.Width * scale);
        bmp.Height:= Round(jpg.Height * scale);
        bmp.Canvas.StretchDraw(bmp.Canvas.Cliprect, jpg);
        {Draw thumbnail as control}
        Self.Canvas.Draw(100, 10, bmp);
        {Convert back to JPEG and save to file}
        jpg.Assign(bmp);
        jpg.SaveToFile(
          ChangeFileext(opendialog1.filename, '_thumb.JPG')
        );
      finally
        bmp.free;
      end;
    finally
      jpg.free;
    end;
  end;
end;

Note: to test this code you need to drop a TButton and a TOpenDialog on a form and add the JPEG unit to the uses statement.

Original resource: The Delphi Pool
Author: Peter Below
Added: 2009/09/14
Last updated: 2009/09/14