How to save a png file with transparency?

强颜欢笑 提交于 2019-12-01 05:27:26

This approach works for me:

uses GR32, GR32_PNG, GR32_PortableNetworkGraphic;

var
  Y: Integer;
  X: Integer;
  Png: TPortableNetworkGraphic32;

  function IsWhite(Color32: TColor32): Boolean;
  begin
    Result:= (TColor32Entry(Color32).B = 255) and
             (TColor32Entry(Color32).G = 255) and
             (TColor32Entry(Color32).R = 255);
  end;

begin
  with Image321 do
  begin
    Bitmap.ResetAlpha;
    for Y := 0 to Bitmap.Height-1 do
      for X := 0 to Bitmap.Width-1 do
      begin
        if IsWhite(Bitmap.Pixel[X, Y]) then
          Bitmap.Pixel[X,Y]:=Color32(255,255,255,0);
      end;
    Png:= TPortableNetworkGraphic32.Create;
    Png.Assign(Bitmap);
    Png.SaveToFile('C:\Temp\NowTransparent.png');
    Png.Free;
  end;
end;

This uses the GR32 PNG library. It's a pretty direct way, setting all white pixels to transparent.

PS: Image321 is a TImage32 component, containing my TBitmap32.

You haven't specified the Delphi version, but if your delphi version has "PngImage"(I believe it comes with D2009+) the code bellow works perfectly(loaded in Gimp and Windows Photo Viewer, it draws a frame and some text with transparent background, feel free to play with it:

uses
  PngImage;

procedure TForm1.OnBtnClick(Sender: TObject);
var
  bmp: TBitmap;
  png: TPngImage;
begin
  bmp := TBitmap.Create;
  bmp.Width := 200;
  bmp.Height := 200;

  bmp.Canvas.Brush.Color := clBlack;
  bmp.Canvas.Rectangle( 20, 20, 160, 160 );

  bmp.Canvas.Brush.Style := bsClear;
  bmp.Canvas.Rectangle(1, 1, 199, 199);

  bmp.Canvas.Brush.Color := clWhite;
  bmp.Canvas.Pen.Color := clRed;
  bmp.Canvas.TextOut( 35, 20, 'Hello transparent world');

  bmp.TransparentColor := clWhite;
  bmp.Transparent := True;

  png := TPngImage.Create;
  png.Assign( bmp );
  png.SaveToFile( 'C:\test.png' );

  bmp.Free;
  png.Free;
end;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!