How to save a png file with transparency?

前端 未结 2 1635
北海茫月
北海茫月 2021-01-13 09:25

I am using Barcode Studio 2011 to paint a QR Code into a Graphics32 - TImage32 Component and I want to save it in png format but with the white colour as transparent this I

2条回答
  •  被撕碎了的回忆
    2021-01-13 09:57

    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.

提交回复
热议问题