How to resize a picture?

Little Helper picture Little Helper · Nov 13, 2011 · Viewed 32.7k times · Source

I have image (500x500) but I need to resize it to 200x200 and paint it on TImage. How to achieve such result?

Note
I know about Stretch property in TImage, but I want to resize the image programmatically.

Answer

Andreas Rejbrand picture Andreas Rejbrand · Nov 13, 2011

If you know that the new dimensions are not greater than the original ones, you can simply do

procedure ShrinkBitmap(Bitmap: TBitmap; const NewWidth, NewHeight: integer);
begin
  Bitmap.Canvas.StretchDraw(
    Rect(0, 0, NewWidth, NewHeight),
    Bitmap);
  Bitmap.SetSize(NewWidth, NewHeight);
end;

I leave it as an exercise to write the corresponding code if you know that the new dimensions are not smaller than the original ones.

If you want a general function, you could do

procedure ResizeBitmap(Bitmap: TBitmap; const NewWidth, NewHeight: integer);
var
  buffer: TBitmap;
begin
  buffer := TBitmap.Create;
  try
    buffer.SetSize(NewWidth, NewHeight);
    buffer.Canvas.StretchDraw(Rect(0, 0, NewWidth, NewHeight), Bitmap);
    Bitmap.SetSize(NewWidth, NewHeight);
    Bitmap.Canvas.Draw(0, 0, buffer);
  finally
    buffer.Free;
  end;
end;

This approach has the downside of doing two pixel-copy operations. I can think of at least two solutions to that problem. (Which?)