How to save a png file with transparency?

前端 未结 2 1643
北海茫月
北海茫月 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 10:05

    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;
    

提交回复
热议问题