Skip to content

Instantly share code, notes, and snippets.

@viniciusfbb
Created November 7, 2022 17:41
Show Gist options
  • Save viniciusfbb/0eb3d2dab0b7e4f78435bdcd44cc03ee to your computer and use it in GitHub Desktop.
Save viniciusfbb/0eb3d2dab0b7e4f78435bdcd44cc03ee to your computer and use it in GitHub Desktop.
Simple example resizing an image using Skia4Delphi
uses
System.UITypes, Skia;
function GetResizedImage(const AImage: ISkImage; const ANewWidth, ANewHeight: Integer): ISkImage;
var
LSurface: ISkSurface;
begin
LSurface := TSkSurface.MakeRaster(ANewWidth, ANewHeight);
LSurface.Canvas.Clear(TAlphaColors.Null);
LSurface.Canvas.Scale(ANewWidth / AImage.Width, ANewHeight / AImage.Height);
LSurface.Canvas.DrawImage(AImage, 0, 0, TSkSamplingOptions.High);
Result := LSurface.MakeImageSnapshot;
end;
procedure TForm1.FormCreate(Sender: TObject);
var
LImage: ISkImage;
begin
LImage := TSkImage.MakeFromEncodedFile('a.png');
LImage := GetResizedImage(LImage, 24, 24);
LImage.EncodeToFile('a.png', 100);
end;
@Volfram007
Copy link

Volfram007 commented Mar 25, 2023

Спасибо за пример. Изменил код с сохранением соотношения сторон и прозрачным фоном вокруг

uses
  System.Math, System.Skia;

function GetResizedImage(const AImage: ISkImage;  const ANewWidth, ANewHeight: Integer): ISkImage;
var
  LSurface: ISkSurface;
  ScaleFactor: Single;
  NewWidth, NewHeight: Integer;
  OffsetX, OffsetY: Integer;
begin
  ScaleFactor := Min(ANewWidth / AImage.Width, ANewHeight / AImage.Height);
  NewWidth := Round(AImage.Width * ScaleFactor);
  NewHeight := Round(AImage.Height * ScaleFactor);
  OffsetX := (ANewWidth - NewWidth) div 2;
  OffsetY := (ANewHeight - NewHeight) div 2;

  LSurface := TSkSurface.MakeRaster(ANewWidth, ANewHeight);
  LSurface.Canvas.Clear(TAlphaColors.Null);
  LSurface.Canvas.Scale(ScaleFactor, ScaleFactor);
  LSurface.Canvas.DrawImage(AImage, OffsetX / ScaleFactor, OffsetY / ScaleFactor, TSkSamplingOptions.High);
  Result := LSurface.MakeImageSnapshot;
end;

@viniciusfbb
Copy link
Author

viniciusfbb commented Oct 4, 2023

@Volfram007 Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment