«« Site Rescued »»

While the site is still going to move from its current host, a new site will now take its place. More Info.

The new site may have less content, but the core will now remain. And it will now play nicely with phones! Keep an eye on the DelphiDabbler Blog for news.

» Help

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

   
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

« Return to contents »