How to correctly resize transparent image in graphisc32?

655 Views Asked by At

Image is bmp with olive transparent color.

type 
  TForm1 = class(TForm)
  ImageList: TImageList;  //
  MainMenu: TMainMenu;    //Standart parameters
  MenuItem: TMenuItem;    //
  procedure FormCreate(Sender: TObject);
...
function ScaleImage(aImage: TBitmap): TBitmap;
var
  Src, Dst: TBitmap32;
  R: TKernelResampler;      
begin
  Src := TBitmap32.Create;
  Src.SetSize(16, 16);
  Src.DrawMode := dmTransparent;
  Src.OuterColor := clOlive;
  Src.Assign(aImage);
  Dst := TBitmap32.Create;
  Dst.SetSize(24,24);
  R := TKernelResampler.Create(Src);
  R.Kernel := TLanczosKernel.Create;
  Dst.DrawMode := dmTransparent;
  Dst.OuterColor := clOlive;
  Dst.Draw(Dst.BoundsRect, Src.BoundsRect, Src);
  Result.Assign(Dst);
end;

procedure AddImage;
var
  Image: TBitmap;
begin
  Image := TBitmap.Create;
  Image.LoadFromResourceName(hInstance,  'BMPNOFILTER');
  ImageList.AddMasked(ScaleImage(Image), clOlive);      
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  AddImage;
  MainMenu.Images := ImageList;
  MenuItem.ImageIndex := 0;
end;

After that result TBitmap to imagelist TImageList with Imagelist.AddMasked(Result, clOlive); but image is drawn with olive color. Trying to resize image without olive color (aImage.transparent := True;), after assign Src background become black and use it as transparent color, ignoring OuterColor value.

Tryed clOlive32 as OuterColor. Result:

Code i used:

var
 R: TKernelResampler;
 Src, Dst: TBitmap32;
 fImage: TBitmap;
 OriginalImage, TranOriginalImage: TImage //16x16
 SrcImage, DstImage, ResultImage: TImage //24x24
...
fImage := TBitmap.Create;
fImage.LoadFromResourceName(hInstance,  'BMPNOFILTER');
OriginalImage.Picture.Bitmap := fImage;
fImage.Transparent := True;
fImage.TransparentColor := clOlive;
TranOriginalImage.Picture.Bitmap := fImage;
TranOriginalImage.Transparent := True;
Src := TBitmap32.Create;
Src.SetSize(16, 16);
Src.OuterColor := clOlive32;
Src.Assign(fImage);
Src.DrawMode := dmTransparent;
Src.OuterColor := clOlive32;
SrcImage.Picture.Bitmap.Assign(Src);
Dst := TBitmap32.Create;
Dst.SetSize(24, 24);
Dst.DrawMode := dmTransparent;
Dst.OuterColor := clOlive32;
R := TKernelResampler.Create(Src);
R.Kernel := TLanczosKernel.Create;
Dst.Draw(Dst.BoundsRect, Src.BoundsRect, Src);
DstImage.Picture.Bitmap.Assign(Dst);
ResultImage.Picture.Bitmap.Assign(Dst);
ResultImage.Transparent := True; 
1

There are 1 best solutions below

2
CWBudde On

You should use the Graphics32 pendant to the olive color. This is clOlive32 instead of clOlive. Along with adding

aImage.transparent := True;

this should do the trick more or less.

Eventually you will see a few glitches as the resampler might not preserve red as red, but use actual resampling to get colors in between around the edges.