Skip to content

Instantly share code, notes, and snippets.

@viniciusfbb
Last active June 21, 2024 11:49
Show Gist options
  • Save viniciusfbb/fe3cf76984216e1a5a91a2e987074b81 to your computer and use it in GitHub Desktop.
Save viniciusfbb/fe3cf76984216e1a5a91a2e987074b81 to your computer and use it in GitHub Desktop.
Resizing image using Skia4Delphi
function GetResizedImage(const AImage: ISkImage; ATargetWidth, ATargetHeight: Integer;
ASamplingOptions: TSkSamplingOptions; AProgressive: Boolean = True): ISkImage;
function MakeResized(const AImage: ISkImage; ANewWidth, ANewHeight: Integer): ISkImage;
var
LSurface: ISkSurface;
begin
LSurface := TSkSurface.MakeRaster(ANewWidth, ANewHeight);
LSurface.Canvas.Clear(0);
LSurface.Canvas.Scale(ANewWidth / AImage.Width, ANewHeight / AImage.Height);
LSurface.Canvas.DrawImage(AImage, 0, 0, ASamplingOptions);
Result := LSurface.MakeImageSnapshot;
end;
var
LNewWidth, LNewHeight: Integer;
begin
if (AImage = nil) or (ATargetWidth <= 0) or (ATargetHeight <= 0) then
Exit(nil);
if AProgressive then
begin
Result := AImage;
while (Result.Width <> ATargetWidth) or (Result.Height <> ATargetHeight) do
begin
if Result.Width < ATargetWidth then
LNewWidth := Min(Result.Width * 2, ATargetWidth)
else if Result.Width > ATargetWidth then
LNewWidth := Max(Round(Result.Width / 2), ATargetWidth)
else
LNewWidth := ATargetWidth;
if Result.Height < ATargetHeight then
LNewHeight := Min(Result.Height * 2, ATargetHeight)
else if Result.Height > ATargetHeight then
LNewHeight := Max(Round(Result.Height / 2), ATargetHeight)
else
LNewHeight := ATargetHeight;
Result := MakeResized(Result, LNewWidth, LNewHeight);
end;
end
else
begin
if (AImage.Width = ATargetWidth) and (AImage.Height = ATargetHeight) then
Exit(AImage);
Result := MakeResized(AImage, ATargetWidth, ATargetHeight);
end;
end;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment