Jump to content
pyscripter

High quality bitmap resize with transparency

Recommended Posts

The Windows imaging Component contains a wealth of useful features for manipulating images in different formats.  Delphi partially encapsulates this functionality into the TWICImage class of Vcl.Graphics which is a TGraphics descendent.  The following code  resizes pf32bit bitmaps with transparency using TWICImage, at a much better quality than can be achieved with StretchDraw for example or anything else I have tried..

 

Uses
  Winapi.Wincodec,
  Vcl.Graphics;

procedure ResizeBitmap(Bitmap: TBitmap; const NewWidth, NewHeight: integer);
var
  Factory: IWICImagingFactory;
  Scaler: IWICBitmapScaler;
  Source : TWICImage;
begin
  Bitmap.AlphaFormat := afDefined;
  Source := TWICImage.Create;
  try
    Factory := TWICImage.ImagingFactory;
    Source.Assign(Bitmap);
    Factory.CreateBitmapScaler(Scaler);
    Scaler.Initialize(Source.Handle, NewWidth, NewHeight,
      WICBitmapInterpolationModeHighQualityCubic);
    Source.Handle := IWICBitmap(Scaler);
    Bitmap.Assign(Source);
    Scaler := nil;
    Factory := nil;
  finally
    Source.Free;
  end;
end;

Some key points:

  • Setting the AlphaFormat to alDefined is crucial for maintaining the transparency.
  • If you do not release the ImageFactory before you destroy the TWICImage you will get access violations next time you call this procedure.  (Have a look at TWICImage .Destroy).
Edited by pyscripter
  • Like 3
  • Thanks 2

Share this post


Link to post

Please note that there is a bug in Vcl.Graphics which affects the code above.

Edited by pyscripter

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×