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;`
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;
Found this answer, try putting this in the Code:
bmp.TransparentColor := bmp.Canvas.Pixels[0,0];
Then put insto
bmp.Transparent := True
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);