Search code examples
delphidelphi-10-seattle

Resize images and save output


I see many questions/Answers about resizing images here on SO.

But I can't find the correct one that fit my case.

In this post, it works only when you want to have a small image from a big one.

However if you have a picture with 24x24 dimension and you want to resize it to 256x256 dimension, the procedure will fail and gives you a distorted picture.

The code below is my attempt to sort out my issue

  Graph := TBitmap.Create;
  try   // After loading a .bmp file to Image1 with 48x48 dimension 
    Graph.Assign( Image1.Picture.Bitmap );
    Graph.Canvas.StretchDraw(Rect(0, 0, 255, 255), Graph);
    Graph.SetSize(255,255);
    Graph.SaveToFile('Location\Resault.bmp');
  finally
    Graph.Free;
  end;

The original image:

enter image description here

The result (the white square with the black part on the upper left):

enter image description here

How can we load an image to a TImage and convert/resize it and save changes?


Solution

  • Thanks to kobik for the comment, it was useful.

    var Graph : TBitmap; Conv : TBitmap;
    begin
    
          Graph := TBitmap.Create;
          try
            Graph.Assign( Image1.Picture.Bitmap );
            Conv := TBitmap.Create;
            try
              Conv.SetSize(255,255);
              Conv.Canvas.StretchDraw(Rect(0, 0, 255, 255), Graph);
              Conv.SaveToFile('Location\Resault.bmp');   
            finally
              Conv.Free;
            end;
    
          finally
            Graph.Free;
          end;
    
    end;