How to put white / transparent background on PNG image that is with black background

I'm using this code in lazarus but at the time of saving it shows a black part like the one in the image, I wanted it to be white/transparent. I tested a few ways and it didn't work out.

  procedure TformMain.btSalvarImagemClick(Sender: TObject);
  var
  bmp: TBitmap;
  R: TRect;
  png : TPortableNetworkGraphic;
  begin
  // bmp, png
  bmp := TBitmap.Create;
  png := TPortableNetworkGraphic.Create;
  try
  // bmp
  if SavePictureDialog1.Execute then
  begin
  R := Rect(500, 500, BarcodeQR1.Width, BarcodeQR1.Height);
  bmp.SetSize(600, 600);
  bmp.Canvas.Brush.Color := clWhite;
  bmp.Canvas.FillRect®;
  BarcodeQR1.PaintOnCanvas(bmp.Canvas, R);
  png.Assign(bmp);
  png.SaveToFile(SavepictureDialog1.Filename);
  end;
  finally
  bmp.Free;
  png.Free;
  end;
  end;`

QrCode

Author: Wanderson Rodrigo, 2019-02-12

3 answers

I got

procedure TformMain.btSalvarImagem1Click(Sender: TObject); var bmp: TBitmap; R: TRect; png : TPortableNetworkGraphic; begin // bmp, png bmp := TBitmap.Create; png := TPortableNetworkGraphic.Create; try // bmp if SavePictureDialog1.Execute then begin BarcodeQR2.Height := 600; BarcodeQR2.Width := 600; R := Rect(0, 0, BarcodeQR2.Width, BarcodeQR2.Height); bmp.SetSize(BarcodeQR2.Width, BarcodeQR2.Height); bmp.Canvas.Brush.Color := clWhite; bmp.Canvas.FillRect(R); BarcodeQR2.PaintOnCanvas(bmp.Canvas, R); png.Assign(bmp); png.SaveToFile(SavepictureDialog1.Filename); BarcodeQR2.Height := 120; BarcodeQR2.Width := 105; end; finally bmp.Free; png.Free; end; end;

QRCode

 4
Author: Jackson Felipe Magnabosco, 2019-02-12 17:35:31

Found this answer, try putting this in the Code:

 bmp.TransparentColor := bmp.Canvas.Pixels[0,0];

Then put insto

 bmp.Transparent := True
 1
Author: Wanderson Rodrigo, 2019-02-12 12:06:46

Replace the snippet:

  png.Assign(bmp);
  png.SaveToFile(SavepictureDialog1.Filename);

By:

  png.PixelFormat := pf32bit;
  png.Transparent := True;
  png.TransparentColor := clWhite;
  png.Assign(bmp);
  png.SaveToFile(SavepictureDialog1.Filename);
 1
Author: Augusto Vasques, 2019-02-12 12:46:44